类库连接数据库
第三方组件: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