類庫連接資料庫
第三方組件:Mysql.Data.dll
說明:去官方網站下載Mysql.Data.dll,然後在項目中添加該組件的引用,在代碼頁里輸入using Mysql.Data.MysqlClient,我們就可以順利的使用該類庫的函數建立連接了。
以下是幾個常用函數:
#region 建立MySql資料庫連接
/// <summary>
/// 建立資料庫連接.
/// </summary>
/// <returns>返回MySqlConnection對象</returns>
public MySqlConnection getmysqlcon()
{
string M_str_sqlcon = "server=localhost;user id=root;password=root;database=abc"; //根據自己的設置
MySqlConnection myCon = new MySqlConnection(M_str_sqlcon);
return myCon;
}
#endregion
#region 執行MySqlCommand命令
/// <summary>
/// 執行MySqlCommand
/// </summary>
/// <param name="M_str_sqlstr">SQL語句</param>
public void getmysqlcom(string M_str_sqlstr)
{
MySqlConnection mysqlcon = this.getmysqlcon();
mysqlcon.Open();
MySqlCommand mysqlcom = new MySqlCommand(M_str_sqlstr, mysqlcon);
mysqlcom.ExecuteNonQuery();
mysqlcom.Dispose();
mysqlcon.Close();
mysqlcon.Dispose();
}
#endregion
#region 創建MySqlDataReader對象
/// <summary>
/// 創建一個MySqlDataReader對象
/// </summary>
/// <param name="M_str_sqlstr">SQL語句</param>
/// <returns>返回MySqlDataReader對象</returns>
public MySqlDataReader getmysqlread(string M_str_sqlstr)
{
MySqlConnection mysqlcon = this.getmysqlcon();
MySqlCommand mysqlcom = new MySqlCommand(M_str_sqlstr, mysqlcon);
mysqlcon.Open();
MySqlDataReader mysqlread = mysqlcom.ExecuteReader(CommandBehavior.CloseConnection);
return mysqlread;
}
#endregion