轉 http://wenku.baidu.com/view/d0cf34708e9951e79b8927c7.htmlhtml
C# 鏈接MYSQL數據庫的方法及示例mysql
鏈接MYSQL數據庫的方法及示例
方法一:web
using MySql.Data
using MySql.Data.MySqlClient;
其餘操做跟SQL是差很少,無非就是前綴變成MySql了.
補充:
下面是鏈接字符串,供參考.
MySqlConnection con = new MySql.Data.MySqlClient.MySqlConnection("Database='testdb';Data Source='localhost';User Id='db';Password='apple';charset='utf8'");
con.Open();
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = con;
使用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)
{
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();
}
} sql
1、用MySQLDriverCS鏈接MySQL數據庫數據庫
先下載和安裝MySQLDriverCS,地址:c#
http://sourceforge.net/projects/mysqldrivercs/app
在安裝文件夾下面找到MySQLDriver.dll,而後將MySQLDriver.dll添加引用到項目中asp.net
注:我下載的是版本是 MySQLDriverCS-n-EasyQueryTools-4.0.1-DotNet2.0.exe數據庫設計
using System;工具
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Odbc;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MySQLDriverCS;
namespace mysql
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
MySQLConnection conn = null;
conn = new MySQLConnection(new MySQLConnectionString("localhost", "inv", "root", "831025").AsString);
conn.Open();
MySQLCommand commn = new MySQLCommand("set names gb2312", conn);
commn.ExecuteNonQuery();
string sql = "select * from exchange ";
MySQLDataAdapter mda = new MySQLDataAdapter(sql, conn);
DataSet ds = new DataSet();
mda.Fill(ds, "table1");
this.dataGrid1.DataSource = ds.Tables["table1"];
conn.Close();
}
}
}
2、經過ODBC訪問mysql數據庫:
參考:http://www.microsoft.com/china/community/Column/63.mspx
1. 安裝Microsoft ODBC.net:我安裝的是mysql-connector-odbc-3.51.22-win32.msi
2. 安裝MDAC 2.7或者更高版本:我安裝的是mdac_typ.exe 2.7簡體中文版
3. 安裝MySQL的ODBC驅動程序:我安裝的是 odbc_net.msi
4. 管理工具 -> 數據源ODBC –>配置DSN…
5. 解決方案管理中添加引用 Microsoft.Data.Odbc.dll(1.0.3300)
6. 代碼中增長引用 using Microsoft.Data.Odbc;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Linq; //vs2005好像沒有這個命名空間,在c#2008下測試自動生成的
using System.Text
using System.Windows.Forms;
using Microsoft.Data.Odbc;
namespace mysql
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string MyConString = "DRIVER={MySQL ODBC 3.51 Driver};" +
"SERVER=localhost;" +
"DATABASE=inv;" +
"UID=root;" +
"PASSWORD=831025;" +
"OPTION=3";
OdbcConnection MyConnection = new OdbcConnection(MyConString);
MyConnection.Open();
Console.WriteLine("\n success, connected successfully !\n");
string query = "insert into test values( ''hello'', ''lucas'', ''liu'')";
OdbcCommand cmd = new OdbcCommand(query, MyConnection);
//處理異常:插入重複記錄有異常
try{
cmd.ExecuteNonQuery();
}
catch(Exception ex){
Console.WriteLine("record duplicate.");
}finally{
cmd.Dispose();
}
//***********************用read方法讀數據到textbox**********************
string tmp1 = null;
string tmp2 = null;
string tmp3 = null;
query = "select * from test ";
OdbcCommand cmd2 = new OdbcCommand(query, MyConnection);
OdbcDataReader reader = cmd2.ExecuteReader();
while (reader.Read())
{
tmp1 = reader[0].ToString();
tmp2 = reader[1].ToString();
tmp3 = reader[2].ToString();
}
this.textBox1.Text = tmp1 + " " + tmp2 + " " + tmp3;
*/
//************************用datagridview控件顯示數據表**************************
string MyConString = "DRIVER={MySQL ODBC 3.51 Driver};" +
"SERVER=localhost;" +
"DATABASE=inv;" +
"UID=root;" +
"PASSWORD=831025;" +
"OPTION=3";
OdbcConnection MyConnection = new OdbcConnection(MyConString);
OdbcDataAdapter oda = new OdbcDataAdapter("select * from customer ", MyConnection);
DataSet ds = new DataSet();
oda.Fill(ds, "employee");
this.dataGridView1.DataSource = ds.Tables["employee"];
*/
MyConnection.Close();
}
}
}
文章出處:http://www.diybl.com/course/4_webprogram/asp.net/asp_netshl/2008429/112011.html
1、用MySQLDriverCS鏈接MySQL數據庫
先下載和安裝MySQLDriverCS,地址:
http://sourceforge.net/projects/mysqldrivercs/
在安裝文件夾下面找到MySQLDriver.dll,而後將MySQLDriver.dll添加引用到項目中
注:我下載的是版本是 MySQLDriverCS-n-EasyQueryTools-4.0.1-DotNet2.0.exe
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Odbc;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MySQLDriverCS;
namespace mysql
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
MySQLConnection conn = null;
conn = new MySQLConnection(new MySQLConnectionString("localhost", "inv", "root", "831025").AsString);
conn.Open();
MySQLCommand commn = new MySQLCommand("set names gb2312", conn);
commn.ExecuteNonQuery();
string sql = "select * from exchange ";
MySQLDataAdapter mda = new MySQLDataAdapter(sql, conn);
DataSet ds = new DataSet();
mda.Fill(ds, "table1");
this.dataGrid1.DataSource = ds.Tables["table1"];
conn.Close();
}
}
}
2、經過ODBC訪問mysql數據庫:
參考:http://www.microsoft.com/china/community/Column/63.mspx
1. 安裝Microsoft ODBC.net:我安裝的是mysql-connector-odbc-3.51.22-win32.msi
2. 安裝MDAC 2.7或者更高版本:我安裝的是mdac_typ.exe 2.7簡體中文版
3. 安裝MySQL的ODBC驅動程序:我安裝的是 odbc_net.msi
4. 管理工具 -> 數據源ODBC –>配置DSN…
5. 解決方案管理中添加引用 Microsoft.Data.Odbc.dll(1.0.3300)
6. 代碼中增長引用 using Microsoft.Data.Odbc;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Linq; //vs2005好像沒有這個命名空間,在c#2008下測試自動生成的
using System.Text;
using System.Windows.Forms;
using Microsoft.Data.Odbc;
namespace mysql
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string MyConString = "DRIVER={MySQL ODBC 3.51 Driver};" +
"SERVER=localhost;" +
"DATABASE=inv;" +
"UID=root;" +
"PASSWORD=831025;" +
"OPTION=3";
OdbcConnection MyConnection = new OdbcConnection(MyConString);
MyConnection.Open();
Console.WriteLine("\n success, connected successfully !\n");
string query = "insert into test values( ''hello'', ''lucas'', ''liu'')";
OdbcCommand cmd = new OdbcCommand(query, MyConnection);
//處理異常:插入重複記錄有異常
try{
cmd.ExecuteNonQuery();
}
catch(Exception ex){
Console.WriteLine("record duplicate.");
}finally{
cmd.Dispose();
}
//***********************用read方法讀數據到textbox**********************
string tmp1 = null;
string tmp2 = null;
string tmp3 = null;
query = "select * from test ";
OdbcCommand cmd2 = new OdbcCommand(query, MyConnection);
OdbcDataReader reader = cmd2.ExecuteReader();
while (reader.Read())
{
tmp1 = reader[0].ToString();
tmp2 = reader[1].ToString();
tmp3 = reader[2].ToString();
}
this.textBox1.Text = tmp1 + " " + tmp2 + " " + tmp3;
*/
//************************用datagridview控件顯示數據表**************************
string MyConString = "DRIVER={MySQL ODBC 3.51 Driver};" +
"SERVER=localhost;" +
"DATABASE=inv;" +
"UID=root;" +
"PASSWORD=831025;" +
"OPTION=3";
OdbcConnection MyConnection = new OdbcConnection(MyConString);
OdbcDataAdapter oda = new OdbcDataAdapter("select * from customer ", MyConnection);
DataSet ds = new DataSet();
oda.Fill(ds, "employee");
this.dataGridView1.DataSource = ds.Tables["employee"];
*/
MyConnection.Close();
}
}
}
文章出處:http://www.diybl.com/course/4_webprogram/asp.net/asp_netshl/2008429/112011.html
C#鏈接mysql數據庫 |
|
1.鏈接:
1.安裝Microsoft ODBC.net。
2.安裝MySQL的ODBC驅動程序。
2.解決方案管理中添加引用Microsoft.Data.Odbc.dll(1.0.3300)
3.代碼中增長引用
using Microsoft.Data.Odbc;
4.編寫代碼
string MyConString = "DRIVER={MySQL ODBC 3.51 Driver};" +
"SERVER=localhost;" +
"DATABASE=samp_db;" +
"UID=root;" +
"PASSWORD=;" +
"OPTION=3";
//Connect to MySQL using Connector/ODBC
OdbcConnection MyConnection = new OdbcConnection(MyConString);
MyConnection.Open();
Console.WriteLine("\n !!! success, connected successfully !!!\n");
MyConnection.Close();
2.所有例程:
/**
* @sample : mycon.cs
* @purpose : Demo sample for ODBC.NET using Connector/ODBC
* @author : Venu, venu@mysql.com
*
* (C) Copyright MySQL AB, 1995-2003
*
**/
/* build command
*
* csc /t:exe
* /out:mycon.exe mycon.cs
* /r:Microsoft.Data.Odbc.dll
*/
using Console = System.Console;
using Microsoft.Data.Odbc;
namespace myodbc3
{
class mycon
{
static void Main(string[] args)
{
try
{
//Connection string for Connector/ODBC 2.50
/*string MyConString = "DRIVER={MySQL};" +
"SERVER=localhost;" +
"DATABASE=test;" +
"UID=venu;" +
"PASSWORD=venu;" +
"OPTION=3";
*/
//Connection string for Connector/ODBC 3.51
string MyConString = "DRIVER={MySQL ODBC 3.51 Driver};" +
"SERVER=localhost;" +
"DATABASE=test;" +
"UID=venu;" +
"PASSWORD=venu;" +
"OPTION=3";
//Connect to MySQL using Connector/ODBC
OdbcConnection MyConnection = new OdbcConnection(MyConString);
MyConnection.Open();
Console.WriteLine("\n !!! success, connected successfully !!!\n");
//Display connection information
Console.WriteLine("Connection Information:");
Console.WriteLine("\tConnection String:" + MyConnection.ConnectionString);
Console.WriteLine("\tConnection Timeout:" + MyConnection.ConnectionTimeout);
Console.WriteLine("\tDatabase:" + MyConnection.Database);
Console.WriteLine("\tDataSource:" + MyConnection.DataSource);
Console.WriteLine("\tDriver:" + MyConnection.Driver);
Console.WriteLine("\tServerVersion:" + MyConnection.ServerVersion);
//Create a sample table
OdbcCommand MyCommand = new OdbcCommand("DROP TABLE IF EXISTS my_odbc_net",MyConnection);
MyCommand.ExecuteNonQuery();
MyCommand.CommandText = "CREATE TABLE my_odbc_net(id int, name varchar(20), idb bigint)";
MyCommand.ExecuteNonQuery();
//Insert
MyCommand.CommandText = "INSERT INTO my_odbc_net VALUES(10,'venu', 300)";
Console.WriteLine("INSERT, Total rows affected:" + MyCommand.ExecuteNonQuery());;
//Insert
MyCommand.CommandText = "INSERT INTO my_odbc_net VALUES(20,'mysql',400)";
Console.WriteLine("INSERT, Total rows affected:" + MyCommand.ExecuteNonQuery());
//Insert
MyCommand.CommandText = "INSERT INTO my_odbc_net VALUES(20,'mysql',500)";
Console.WriteLine("INSERT, Total rows affected:" + MyCommand.ExecuteNonQuery());
//Update
MyCommand.CommandText = "UPDATE my_odbc_net SET id=999 WHERE id=20";
Console.WriteLine("Update, Total rows affected:" + MyCommand.ExecuteNonQuery());
//COUNT(*)
MyCommand.CommandText = "SELECT COUNT(*) as TRows FROM my_odbc_net";
Console.WriteLine("Total Rows:" + MyCommand.ExecuteScalar());
//Fetch
MyCommand.CommandText = "SELECT * FROM my_odbc_net";
OdbcDataReader MyDataReader;
MyDataReader = MyCommand.ExecuteReader();
while (MyDataReader.Read())
{
if(string.Compare(MyConnection.Driver,"myodbc3.dll") == 0) {
Console.WriteLine("Data:" + MyDataReader.GetInt32(0) + " " +
MyDataReader.GetString(1) + " " +
MyDataReader.GetInt64(2)); //Supported only by Connector/ODBC 3.51
}
else {
Console.WriteLine("Data:" + MyDataReader.GetInt32(0) + " " +
MyDataReader.GetString(1) + " " +
MyDataReader.GetInt32(2)); //BIGINTs not supported by Connector/ODBC
}
}
//Close all resources
MyDataReader.Close();
MyConnection.Close();
}
catch (OdbcException MyOdbcException)//Catch any ODBC exception ..
{
for (int i=0; i < MyOdbcException.Errors.Count; i++)
{
Console.Write("ERROR #" + i + "\n" +
"Message: " + MyOdbcException.Errors[i].Message + "\n" +
"Native: " + MyOdbcException.Errors[i].NativeError.ToString() + "\n" +
"Source: " + MyOdbcException.Errors[i].Source + "\n" +
"SQL: " + MyOdbcException.Errors[i].SQLState + "\n");
}
}
}
}
}
3.使用dataset填充dataGrid:
OdbcConnection con = new OdbcConnection("DRIVER={MySQL ODBC 3.51 Driver};" +
"SERVER=glf;" +
"DATABASE=qxk_db;" +
"UID=root;" +
"PASSWORD=;" +
"OPTION=3");
da=new OdbcDataAdapter("select * from achi_eval",con);
ds=new DataSet();
da.Fill(ds,"customers");
dtSource = ds.Tables["customers"];
pageSize=20;
maxRec = dtSource.Rows.Count;
PageCount = maxRec / pageSize;
if ((maxRec % pageSize) > 0)
{
PageCount += 1;
}
currentPage = 1;
recNo = 0;
LoadPage();
這是前一段須要用到,精選了一些資料,但願對你們有幫助.