1、使用C#與Mysql server進行連線則必須先至Mysql 網站下載Mysql library for C#。
2、Download : no-install version of Mysql library
3、Add Mysql library to our project :
並在在專案的一開始加入using MySql.Data.MySqlClient;
4.首先使用MySqlConnection 物件來與Mysql進行連線:
Ex:
MySqlConnection conn = new MysqlConnection(
"server=192.168.10.110;prot=5306;
user id=mysql; password=123abc;
database=test;pooling=false"
);
conn.open <== 開啟連線
conn.close <== 關閉連線
5. 在與Mysql建立連線後則可以使用MysqlDataAdapter 物件取得資料庫中的所需的資料;並且把取得到
的資料使用C#的DataGridView物件和DataSet物件來進行資料的顯示與管理:
EX:
MySqlDataAdapter AD = new MySqlDataAdapter ( "select * from student_info", conn);
AD.Fill(dataset,"student_info");
dataGridView1.source = dataset.table["student_info"];
6. 當需要對資料庫進行資料更新時,必須使用MySqlComamnd、GetChange 和Update等函式來對資料庫
進行批次更新;另外也可以只使用MysqlCommand來直接進行更新、修改和刪除的行為:
EX:
MySqlDataAdapter da = new MysqlDataAdapter("select * from student_info",conn);
MySqlCommand SqlInsert = new MysqlCommand("insert into student_ifno
(NO,NAME,BIRTHDAY,…) value (@NO,@NAME,@BIRTHDAY,…)",conn);
da.InsertCommand = SqlInsert;
// "@NO" - 變數名稱 "NO"-資料來源的欄位名稱在此為 dataset.table["student"]中的欄位名稱
da.InsertCommand.Parameter.Add("@NO",MySqlDbType.VarChar,8,"NO");
…(針對資料庫中欄位的資料型態來設定相關的參數)
MySqlCommand SqlUpdate = new MysqlCommand(
"Update student_info set NAME=@NAME,… where NO=@NO",conn);
da.UpdateCommand = SqlUpdate;
da.UpdateCommand.Parameter.add("@NO",MysqlDbType.VarChar,8,"NO");
…(針對資料庫中欄位的資料型態來設定相關的參數)
MySqlCommand SqlDelete = new
MySqlCommand("Delete from student_info where NO=@NO",conn);
da.DeleteCommand = SqlDelete;
da.DeleteCommand.Parameter.Add("@NO,MysqlDbType.VarChar,8,"NO");
DataTable UpDataSet = this.dataset.Table["student"].GetChanges();
if (UpDataTable != null) {da.Update(UpDataTable);}
另外如果要單獨執行命令時可以使用MysqlCommand.ExecuteNonQuery()函式。
PS:在執行Sample Code時必須先在Mysql中的test database建立student_info-
Download : MysqlLibrarySample(Source).zip MysqlLibrarySample(EXE).zip
Result :

*****
*****
您好 請問如果我想要少一個或多個欄位應該要修改哪些部分 ,例如想要刪掉grade這個欄位,我已經把有出現grade的部分都刪掉了 例如string MysqlStr = "insert into student_info (NO,NAME,BIRTHDAY,AGE,TEL,CITY,COUNTRY,GRADE) value(";//把裡面的grade拿掉 MysqlStr = MysqlStr + "GRADE='" + this.Example2_Grade.Text + "' ";//此行刪除 還有其他跟grade有關的部分刪掉後 程式還是會出現錯誤 請問是有哪裡還需要修改嗎? 希望您不吝指教 謝謝~
請問一下,我在b電腦寫c#,server的地方我寫a電腦的ip,但是不知道為什麼編譯完要連線的時候,open這行出現unable to connect的錯誤訊息,我該如何解決? 謝謝
hi, 連接字串的部分拼錯了 prot -> port