用c#连接MySQL数据库需要用到mysql-connector-net,这个组件网上查找就可以下载,安装直接按next,按默认路径安装;
(2)新建一个Winfrom工程后,引用这个组件
在解决方案资源管理器中右键引用->添加引用->浏览,浏览路径为安装mysql-connector-net的路径,如我的路径为:C:\Program Files (x86)\MySQL\MySQL Connector Net 6.6.4\Assemblies\v2.0
选择MySql.Data.dll,再确定
(3)在工程中添加:
using MySql.Data.MySqlClient;
using System.Data.SqlClient;
///
/// 建立数据库连接.
///
///返回MySqlConnection对象
public MySqlConnection getmysqlcon()
{
//http://sosoft.cnblogs.com/
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命令
///
/// 执行MySqlCommand
///
/// SQL语句
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对象
///
/// 创建一个MySqlDataReader对象
///
/// SQL语句
///返回MySqlDataReader对象
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;
}