c#怎么链接mysql数据库
1个回答
展开全部
用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;
/// <summary>
/// 建立数据库连接.
/// </summary>
/// <returns>返回MySqlConnection对象</returns>
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命令
/// <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;
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询
广告 您可能关注的内容 |