连接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
连接MySQL数据库的方法及示例方法二:
通过ODBC访问MySQL数据库
访问前要先下载两个组件:odbc.net和MySQL的ODBC驱动(MySQL Connector/ODBC (MyODBC)
driver)目前为3.51版
安装完成后,即可通过ODBC访问MySQL数据库
连接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)
{
Console.WriteLine(msdr.GetString(0));
}
}
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)
{
Console.WriteLine(msdr.GetString(0));
}
}
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)
{
Console.WriteLine(msdr.GetString(0));
}
}
msdr.Close();
mycn.Close();
}
public static void Main()
{
ConnectMySQL ms = new ConnectMySQL();
ms.Connect_CoreLab();
ms.Connect_Odbc();
Connect_Net();
}
}
2014-07-13 16:26:18