天天看點

簡單講講C#通路MySQL資料庫的方法一、C#通路MySQL的驅動程式下載下傳二、使用MySQL動态庫三、連接配接到MySQL資料庫四、資料庫查詢語句的執行五、總結

一、C#通路MySQL的驅動程式下載下傳

http://dev.mysql.com/downloads/file.php?id=405442

mysql-connector-net-6.3.8.msi

安裝mysql-connector-net

二、使用MySQL動态庫

在vs2012中,在工程的引用中加入MySql.Data.dll

三、連接配接到MySQL資料庫

MySqlConnection conn = new MySqlConnection();
string connStr = String.Format("server={0};user={1}; password={2}; database=mysql; pooling=false",
                sServer, sUser, sPassword);
conn.ConnectionString = connStr;

try
  {
    Console.WriteLine("Connecting to MySQL...");
    conn.Open();
    // Perform database operations
  }
  catch (Exception ex)
  {
    Console.WriteLine(ex.ToString());
    return 1;
  }
           

四、資料庫查詢語句的執行

這裡僅介紹了select語句的執行,使用ExecuteReader函數。更新和删除語句有另外的MySqlCommand的函數來處理。

string sql = string.Format("SELECT networkperiod, parttype FROM alldb.part WHERE partid = {0}",
                iPartId);

MySqlCommand cmd = new MySqlCommand(sql, conn);
MySqlDataReader rdr = cmd.ExecuteReader();

if (rdr.HasRows)
{
   rdr.Read();

   int iPeriod = rdr.GetInt32(0);
   int iPartType = rdr.GetInt32(1);
}
rdr.Close();
           

這裡先判斷了rdr是否有資料,然後使用Read(),否則會有異常抛出。

五、總結

使用C#通路MySQL還比較簡單,值得一試。