c#串連mysql類需要安裝mysql-connector-net-5.0.6.zip 並添加引用連接字串:data source=127.0.0.1;user id=root;pwd=;initial catalog=test;allow zero datetime=trueusing System;using System.Collections.Generic;using System.Text;using System.Data;using MySql.Data.MySqlClient;using System.IO;using System.Windows.Forms;namespace WindowsApplication1{ class DataConn { private MySqlConnection myConnection; private MySqlCommand myCommand; private MySqlDataAdapter myAdapter; private MySqlTransaction myTransaction; //建立DB串連 public void getConnection() { StreamReader din = File.OpenText("TextFile.ini"); string contString = din.ReadLine(); try{ myConnection = new MySqlConnection(); myConnection.ConnectionString =contString; myConnection.Open(); } catch (Exception ex) { Console.WriteLine(ex); MessageBox.Show("串連失敗!"); } } //資料查詢操作 public DataTable executeQuery(String sql){ DataTable myTable; try{ myCommand = myConnection.CreateCommand(); myCommand.CommandText = sql; myAdapter= new MySqlDataAdapter(myCommand); DataSet mySet = new DataSet(); myAdapter.Fill(mySet, "selectDa"); myTable = mySet.Tables["selectDa"]; return myTable; }catch(Exception ex){ Console.WriteLine(ex); myTable = new DataTable(); MessageBox.Show("資料發生錯誤!"); return myTable; } } //資料插入,刪除,更新操作 public Boolean executeUpdate(String sql) { try{ myCommand = myConnection.CreateCommand(); myCommand.CommandText = sql; myCommand.ExecuteNonQuery(); if (myTransaction == null) { myConnection.Close(); myConnection = null; } return true; }catch(Exception ex){ if (myTransaction != null) { myTransaction.Rollback(); myTransaction = null; MessageBox.Show("資料發生錯誤,正在啟用交易回復!"); } else if (myConnection == null) { MessageBox.Show("請啟用事務!"); } else { MessageBox.Show("發生錯誤!"); } Console.WriteLine(ex); return false; } } //建立事務 public void createTransaction() { try { myTransaction = myConnection.BeginTransaction(); } catch (Exception ex) { Console.WriteLine(ex); MessageBox.Show("啟用事務失敗!"); } } //提交事務 public void commitTransaction() { try { if (myTransaction != null) myTransaction.Commit(); } catch (Exception ex) { myTransaction.Rollback(); Console.WriteLine(ex); MessageBox.Show("資料發生錯誤,正在啟用交易回復!"); } finally { myConnection.Close(); myConnection = null; } } }}
mysql-connector-net:http://mysql.isu.edu.tw/downloads/connector/net/5.2.html