第三方组件: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
引用这个Mysql.Data.dll之后
using MySql.Data.MySqlClient; public void GetConn() { MySqlConnection objConn = new MySqlConnection(); objConn.ConnectionString = "data source=localhost;user id=root;password=123;initial catalog=game "; objConn.Open(); MySqlCommand objCmd = new MySqlCommand("delete from xxx",objConn); int i = objCmd.ExecuteNonQuery(); objConn.Close(); }
是写在方法里面的看下面的简单例子(插入方法) 或许能给你灵感
public int insertinto(Entity entity)
{
string connstring = "server=.;uid=sa;pwd=accp;databser=MyQQ";//这是连接数据库的代码它是放在方法里面的
SqlConnection conn = new SqlConnection(connstring))
string sql = string.Format("insert into user(uid,pwd) values('{0}',{1})","apple",123456);
SqlCommand comm = new SqlCommand(sql,conn);
conn.Open();
int result = comm.ExecuteNonQuery();
conn.Close();
return result;
}