2009/07/02

MySQL Connector/Net 使用法

1. 安裝 MySQL Connector/Net (參考文章)
2. 開啟 Visual C# 2008,將 MySql.Data 加入物件瀏覽器的自訂元件集(編輯自訂元件集),在.NET分頁可以找到 MySql.Data。



3. 在專案要先「參考」MySql.Data才能在專案中使用,快速新增參考的方式很簡單,在 2. 項中我們已經新增了 MySql.Data,只要選取後按下圖中的按鈕就可以快速加入參考。



4. 以下是連接 MySQL 資料庫的範例程式碼:

using System;
using System.Windows.Forms;
using MySql.Data.MySqlClient;


namespace WindowsFormsApplication1 {
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e) {
MySqlConnection conn = new MySqlConnection("server=localhost;user=root;database=test;port=3306;charset=utf8;");
try {
conn.Open();
MySqlCommand cmd = new MySqlCommand("SELECT * FROM test", conn);
MySqlDataReader rdr = cmd.ExecuteReader();

while(rdr.Read()) {
this.label1.Text += rdr[0] + " -- " + rdr[1] + "\n";
}

rdr.Close();
conn.Close();
} catch(Exception ex) {
MessageBox.Show(ex.ToString());
}
}
}
}


Form1 有個 Label 叫做 label1,作為顯示資料庫的項目用。

沒有留言:

張貼留言