[更新] C#連接MySQL

[更新] C#連接MySQL

我在五年前(好久遠…)寫過一篇關於C# 連接 MySQL的文章,由於年代久遠MySQL也更新了相關的DLL,所以舊的程式會發生一些錯誤,因此我更新了這段程式,希望對於有使用C#連接到MySQL的朋友有所幫助。

安裝MySQL Connector
1. 首先請先到MySQL官方網站下載新的Connector:Connector/Net 6.2
2. 安裝完畢之後請開啟你的Visual Studio,點選專案名稱後按右鍵,接著點選Add Reference
MySQL Connector Add Reference

3. 按下Add Reference之後會開啟下面的視窗,切換到Browse頁籤,如果剛剛安裝Connector的時候是使用預設的路徑,那麼請切換到C:\Program Files\MySQL\MySQL Connector Net 6.2.1\Assemblies這個路徑,就可以看到跟我截圖一樣的畫面。
Add Reference MySQL Connector Step 2

4. 根據你的需求選擇要加入的DLL,選好之後按下OK,可以在Solution Explorer看到MySql.Data
Add Reference MySQL Connector Step 4

撰寫程式

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MySql.Data;
using MySql.Data.MySqlClient;

namespace mysql
{
class Program
{
static void Main(string[] args)
{
string dbHost = "資料庫位址";
string dbUser = "資料庫使用者名稱";
string dbPass = "資料庫使用者密碼";
string dbName = "資料庫名稱";

// 如果有特殊的編碼在database後面請加上;CharSet=編碼, utf8請使用utf8_general_ci
string connStr = "server="+dbHost+";uid="+dbUser+";pwd="+dbPass+";database="+dbName;
MySqlConnection conn = new MySqlConnection(connStr);

// 連線到資料庫
try
{
conn.Open();
}
catch (MySql.Data.MySqlClient.MySqlException ex) {
switch (ex.Number)
{
case 0:
Console.WriteLine("無法連線到資料庫.");
break;
case 1045:
Console.WriteLine("使用者帳號或密碼錯誤,請再試一次.");
break;
}
}

// 進行select
string SQL = "select plain from yammer order by id desc limit 0,10 ";
try
{
MySqlCommand cmd = new MySqlCommand(SQL, conn);
MySqlDataReader myData = cmd.ExecuteReader();

if (!myData.HasRows)
{
// 如果沒有資料,顯示沒有資料的訊息
Console.WriteLine("No data.");
}
else
{
// 讀取資料並且顯示出來
while (myData.Read())
{
Console.WriteLine("Text={0}", myData.GetString(0));
}
myData.Close();
}
}
catch (MySql.Data.MySqlClient.MySqlException ex) {
Console.WriteLine("Error " + ex.Number + " : " + ex.Message);
}
}
}
}

執行結果,中文也可以正常顯示
C# connect to MySQL Result

如果有任何問題歡迎跟我一起討論

阿維

阿維雜記本的偷懶維護者