C# 连接调用MySQL
2015-07-23 15:55
441 查看
string bDir = AppDomain.CurrentDomain.BaseDirectory; if (SQLConnectedFlag == false) {//未连接 string dllfile = bDir + "libmySQL.dll"; //检查DLL文件 if (File.Exists(dllfile) == false) { DebugOutput.ProcessMessage("missing " + dllfile);//输出到文件 return false; } try { //实例化连接 string strConnection = new MySQLConnectionString(sql_uri, sql_database, sql_user, sql_psw).AsString; //strConnection += ";Connect Timeout=10"; m_mysqlConn = new MySQLConnection(strConnection); //打开连接 m_mysqlConn.Open(); MySQLCommand commn = new MySQLCommand("set names gbk", m_mysqlConn);//设置编码 commn.ExecuteNonQuery(); //commn = new MySQLCommand("set autocommit = 0 ", m_mysqlConn);//禁用自动提交 //commn.ExecuteNonQuery(); SQLConnectedFlag = true; } catch (MySQLException ex) { if (ex.ErrorCode != -2147467259)//连接不上服务器不关注 { DebugOutput.ProcessMessage(ex);//输出到文件 } }
下载C#连接MySql所需的库文件MySQLDriverCS,由两个文件组成libmySQL.dll,MySQLDriverCS.DLL。
将libmySQL.dll拷贝到c:\windows\system32目录下,然后将MySQLDriverCS.DLL引入到C#或ASP.NET工程。
(引入操作:项目右键->添加引用->浏览)
首先导入命名空间
using MySQLDriverCS;
在方法中使用
[csharp] view
plaincopy
MySQLConnection conn = new MySQLConnection(new MySQLConnectionString("数据库IP地址","数据库名" "用户名", "密码").AsString);
MySQLCommand cmd = new MySQLCommand("SQL语句", conn);
conn.Open();
cmd.ExecuteNonQuery();
Conn.Close();
具体代码例子:
[csharp] view
plaincopy
using MySQLDriverCS;
// 建立数据库连接
MySQLConnection DBConn;
DBConn = new MySQLConnection(new MySQLConnectionString("localhost","mysql","root","",3306).AsString);
DBConn.Open();
// 执行查询语句
MySQLCommand DBComm;
DBComm = new MySQLCommand("select Host,User from user",DBConn);
// 读取数据
MySQLDataReader DBReader = DBComm.ExecuteReaderEx();
// 显示数据
try
{
while (DBReader.Read())
{
Console.WriteLine("Host = {0} and User = {1}", DBReader.GetString(0),DBReader.GetString(1));
}
}
finally
{
DBReader.Close();
DBConn.Close();
}
//关闭数据库连接
DBConn.Close();
相关文章推荐
- MySQL中的max_connections和max_user_connections 及 MySQL服务器最大连接数的合理设置
- Ubuntu下查看已安装软件名称/卸载软件
- MYSQL查询
- Mysql(Windows)--- Access denied for user 'root'@'localhost'(using password:YES)
- MySQL Study之--MySQL用户及权限管理
- Mysql 数字类型转换函数
- MySQL使用经验总结
- lamp编译安装
- mysql 分表
- MySQL数据导出与导入
- mysql忘记root密码,修改root密码
- MySQL表损坏预防与修复
- MySQL表损坏预防与修复
- Mysql日期处理方式
- 使用Hibernate和mysql中文乱码问题
- mysql 游标
- mysql 存储过程循环插入数据
- MySQL创建Function时报的1418错误代号解决办法
- MySQL Cluster: Two webserver setup
- MySQL存储过程中的3种循环