#创建SQL Server数据库浅析
时间:2010-11-22 来源:枫-
在创建了数据库连接对象后,我们就可以在程序中运用它了。首先,我们在程序中动态地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(SqlException ae)
- {
- MessageBox.Show(ae.Message.ToString());
- }
- }
相关阅读 更多 +