下载C#连接MySql所需的库文件MySQLDriverCS,由两个文件组成libmySQL.dll,MySQLDriverCS.DLL。
将libmySQL.dll拷贝到c:\windows\system32目录下,然后将MySQLDriverCS.DLL引入到C#或ASP.NET工程。
(引入操作:项目右键->添加引用->浏览)
首先导入命名空间
using MySQLDriverCS;
在方法中使用
- MySQLConnection conn = new MySQLConnection(new MySQLConnectionString("数据库IP地址","数据库名" "用户名", "密码").AsString);
- MySQLCommand cmd = new MySQLCommand("SQL语句", conn);
- conn.Open();
- cmd.ExecuteNonQuery();
- Conn.Close();
具体代码例子:
- 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();
关键字词: