C#創 建SQL Server資料庫
在建立了資料庫連接對象後,我們就可以在程式中運用它了。首先,我們在程式中動態地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());
-
- }
-
- }