您的位置:首页 > 数据库 > MySQL

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();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: