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 :

          

            

                 

 

文章標籤
全站熱搜
創作者介紹
創作者 yunjuihuang 的頭像
yunjuihuang

瑞の資訊備忘錄

yunjuihuang 發表在 痞客邦 留言(4) 人氣(10,801)