連結如下 Connector/Net
並加入參考MySql.Data.dll (2.0)
程式如下
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.IO;
using System.Data;
//加入mysql 類別庫
using MySql.Data;
using MySql.Data.MySqlClient;
namespace ServiceRequestData
{
class ConnectDatabase
{
private string serverAddress;
private string databaseName;
private string userID;
private string password;
private MySqlConnection MysqlConnection;
public ConnectDatabase()
{
Initialize();
}
//資料初始化
private void Initialize()
{
serverAddress = "";//localhost
databaseName = "";
userID = "";
password = "";
string connectionString;
connectionString = "SERVER=" + serverAddress + ";DATABASE=" + databaseName + ";UID=" + userID + ";PWD=" + password;
MysqlConnection = new MySqlConnection(connectionString);
}
//開啟連結到資料庫
private bool ConnectionOpen()
{
try
{
MysqlConnection.Open();
return true;
}
catch (MySqlException ex)
{
//例外處理,常見的兩種錯誤
//ex.Number=0:無法連接到伺服器.
//ex.Number=1045: 無效的使用者名稱或密碼.
switch (ex.Number)
{
case 0:
MessageBox.Show("無法連接到伺服器");
break;
case 1042:
MessageBox.Show("無效的主機名稱");
break;
case 1045:
MessageBox.Show("使用者名稱/密碼錯誤");
break;
}
return false;
}
}
//關閉連結
private bool ConnectionClose()
{
try
{
MysqlConnection.Close();
return true;
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message);
return false;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return false;
}
}
//執行新增刪除修改語法
public void ExeSQL(string SQLstatement) //SQLstatement:SQL語法
{
//open connection
if (this.ConnectionOpen() == true)//開啟連結
{
MySqlCommand command = new MySqlCommand(SQLstatement, MysqlConnection);//new MySQL 指令
command.ExecuteNonQuery();//執行語法
this.ConnectionClose();//關掉連結
}
}
//執行查詢語法,將結果放入Dataset中
public void SelectRead(string SQLstatement,ref DataSet ds, string TableName)
{
if (this.ConnectionOpen() == true)//開啟連結
{
MySqlCommand command = new MySqlCommand(SQLstatement, MysqlConnection);//new MySQL 指令
MySqlDataAdapter sdt = new MySqlDataAdapter(command);
sdt.Fill(ds, TableName); //把查詢結果Table放入dataset
this.ConnectionClose();//關掉連結
}
}
}
}
剛好搜到這篇文章,可是整個網誌只有三篇文章啊
回覆刪除Method ? public void connectDatabase()
回覆刪除