时间:2014-10-17 09:54:26 来源: 复制分享
这里我们主要介绍C#创建sql server数据库,包括介绍通过CREATE TABLE这句SQL语句完成创建表的操作等方面。
在创建了数据库连接对象后,我们就可以在程序中运用它了。首先,我们在程序中动态地C#创建SQL Server数据库。我们将数据库创建在C:\mysql目录下,所以读者要练习该实例的话得先在C:下创建一个名为mysql的文件夹,否则会出错!
创建数据库的关键是函数中的sql对象,通过该对象我们指定了数据库文件的一些基本属性。之后,我们新创建了一个SqlCommand对象,通过该对象我们就实际完成了对数据库的操作。函数的实现如下:
private void button1_Click(object sender, System.EventArgs e)
{
// 打开数据库连接
if( conn.State != ConnectionState.Open) conn.Open();
string sql = "CREATE DATABASE mydb ON PRIMARY" +"(name=test_data,filename = ‘C:\\mysql\\mydb_data.mdf’, size=3," +"maxsize=5,filegrowth=10%)log on" +"(name=mydbb_log,filename=‘C:\\mysql\\mydb_log.ldf’,size=3," +"maxsize=20,filegrowth=1)";
cmd = new SqlCommand(sql, conn);
try
{
cmd.ExecuteNonQuery();
}
catch(SqlException ae)
{
MessageBox.Show(ae.Message.ToString());
}
}
创建了数据库后,我们得为其创建表,表是数据库中的基本对象。我们通过CREATE TABLE这句SQL语句完成创建表的操作,表被创建后,我们就确定了其模式(Schema)。之后,我们还通过INSERT语句向该表中添加了四条记录以为后用。函数的实现如下:
private void button2_Click(object sender, System.EventArgs e)
{
// 打开数据库连接
if( conn.State == ConnectionState.Open) conn.Close();
ConnectionString ="Integrated Security=SSPI;" + "Initial Catalog=mydb;" + "Data Source=localhost;";
conn.ConnectionString = ConnectionString;
conn.Open();
sql = "CREATE TABLE myTable"+ "(myId INTEGER CONSTRAINT PKeyMyId PRIMARY KEY,"+ "myName CHAR(50),
myAddress CHAR(255), myBalance FLOAT)";
cmd = new SqlCommand(sql, conn);
try
{
cmd.ExecuteNonQuery();
// 向表中添加记录
sql = "INSERT INTO myTable(myId, myName, myAddress, myBalance) "+ "VALUES (1001, ‘Puneet Nehra’, ‘A 449 Sect 19, DELHI’, 23.98 ) " ;
cmd = new SqlCommand(sql, conn);
cmd.ExecuteNonQuery();
sql = "INSERT INTO myTable(myId, myName,myAddress, myBalance) "+ "VALUES (1002, ‘Anoop Singh’, ‘Lodi Road, DELHI’, 353.64) " ;
cmd = new SqlCommand(sql, conn);
cmd.ExecuteNonQuery();
sql = "INSERT INTO myTable(myId, myName, myAddress, myBalance) "+ "VALUES (1003, ‘Rakesh M’, ‘Nag Chowk, Jabalpur M.P.’, 43.43) " ;
cmd = new SqlCommand(sql, conn);
cmd.ExecuteNonQuery();
sql = "INSERT INTO myTable(myId, myName, myAddress, myBalance) "+ "VALUES (1004, ‘Madan Kesh’, ‘4th Street, Lane 3, DELHI’, 23.00) " ;
cmd = new SqlCommand(sql, conn);
cmd.ExecuteNonQuery();
}
catch(SqlExceptionae)
{
MessageBox.Show(ae.Message.ToString()); } }
完成此操作后,我们可以在本机的SQL Sever企业管理器中打开mydb数据库并找到该表了。
上一篇:想学photoshop,我想学ps,请问该如何学photoshop
本文地址:软件教程 >> http://www.9xz.net/it/ruanjianjiaocheng/20299.html
下一篇:利用逼真场景合成图片