连接Mysql数据库的方法及示例
方法一:
使用Mysql推出的Mysql Connector/Net is an ADO.NET driver for Mysql
该组件为Mysql为ADO.NET访问Mysql数据库设计的.NET访问组件。
安装完成该组件后,引用命名空间Mysql.Data.MysqlClient;
使用命令行编译时:csc /r:Mysql.Data.dll test.cs
方法二:
通过ODBC访问Mysql数据库
访问前要先下载两个组件:odbc.net和Mysql的ODBC驱动(Mysql Connector/ODBC (MyODBC) driver)目前为3.51版
安装完成后,即可通过ODBC访问Mysql数据库
方法三:
使用CoreLab推出的Mysql访问组件,面向.NET
安装完成后,引用命名空间:CoreLab.Mysql;
使用命令编译时:csc /r:CoreLab.Mysql.dll test.cs
以下为访问Mysql数据库实例
编译指令:csc /r:CoreLab.Mysql.dll /r:Mysql.Data.dll test.cs
using System;
using System.Net;
using System.Text;
using CoreLab.Mysql;
using System.Data.Odbc;
using Mysql.Data.MysqlClient;
class ConnectMysql
{
public void Connect_CoreLab()
{
string constr = "User Id=root;Host=localhost;Database=qing;password=qing";
MysqlConnection mycn = new MysqlConnection(constr);
mycn.Open();
MysqlCommand mycm = new MysqlCommand("select * from shop",mycn);
MysqlDataReader msdr = mycm.ExecuteReader();
while(msdr.Read())
{
if (msdr.HasRows)
}
msdr.Close();
mycn.Close();
}
public void Connect_Odbc()
{
//string MyConString ="DSN=Mysql;UID=root;PWD=qing";
string MyConString = "DRIVER={Mysql ODBC 3.51 Driver};" +
"SERVER=localhost;" +
"DATABASE=test;" +
"UID=root;" +
"PASSWORD=qing;" +
"OPTION=3";
OdbcConnection MyConn = new OdbcConnection(MyConString);
MyConn.Open();
OdbcCommand mycm = new OdbcCommand("select * from hello",MyConn);
OdbcDataReader msdr = mycm.ExecuteReader();
while(msdr.Read())
{
if (msdr.HasRows)
}
msdr.Close();
MyConn.Close();
}
public void Connect_Net()
{
string myConnectionString = "Database=test;Data Source=localhost;User Id=root;Password=qing";
MysqlConnection mycn = new MysqlConnection(myConnectionString);
mycn.Open();
MysqlCommand mycm = new MysqlCommand("select * from hello",mycn);
MysqlDataReader msdr = mycm.ExecuteReader();
while(msdr.Read())
{
if (msdr.HasRows)
}
msdr.Close();
mycn.Close();
}
public static void Main()
{
ConnectMysql ms = new ConnectMysql();
ms.Connect_CoreLab();
ms.Connect_Odbc();
Connect_Net();
}
}