使用ODBC連接MySQL Database
首先,必須先安裝MySQL ODBC Driver,http://dev.mysql.com/downloads/connector/odbc/
# using Odbc libarey
using System.Data.Odbc;
# 建立ODBC connection
OdbcConnection dbconnect = new OdbcConnection();
# 設定ODBC connection字串
String dbconnstr = "Driver={MySQL ODBC 5.1 Driver};Server=127.0.0.1;Database=CSD;User=test; Password=1234;Option=3;";
dbconnect.ConnectionString = dbconnstr;
# 開啟DB連線,並執行SQL command
String sqlstr = "select pk,name from calltype limit 1";
dbconnect.Open();
OdbcCommand lv1_sqlcmd = new OdbcCommand(sqlstr, dbconnect);
# 讀取SQL command執行結果
OdbcDataReader lv1_rs = lv1_sqlcmd.ExecuteReader();
while (lv1_rs.Read()) {
String pk = lv1_rs[0].ToString();
String name = lv1_rs[1].ToString();
}
# 關閉DB連線
dbconnect.Close();
ComboBox分別給予名稱跟值
DataTable skill_dt = new DataTable();
skill_dt.Columns.Add("value");
skill_dt.Columns.Add("name");
skill_dt.Rows.Add("", "請選擇");
skill_dt.Rows.Add("A", "組別1");
skill_dt.Rows.Add("B", "組別2");
skill_dt.Rows.Add("C", "組別3");
skill_dt.Rows.Add("D", "組別4");
skill_dt.Rows.Add("E", "組別5");
skill_dt.Rows.Add("F", "組別6");
skill.DataSource = skill_dt;
skill.DisplayMember = "name";
skill.ValueMember = "value";