废话不说了,直接进入主题,C# ODBC访问MySQL数据库:
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.C# ODBC访问MySQL数据库代码中增加引用 using Microsoft.Data.Odbc;
- usingSystem;
- usingSystem.Collections.Generic;
- usingSystem.ComponentModel;
- usingSystem.Drawing;
- usingSystem.Linq;//vs2005好像没有这个命名空间,在c#2008下测试自动生成的
- usingSystem.Text;
- usingSystem.Windows.Forms;
- usingMicrosoft.Data.Odbc;
- namespacemysql{
- publicpartialclassForm1:Form{
- publicForm1(){
- InitializeComponent();
- }
- privatevoidForm1_Load(objectsender,EventArgse){
- stringMyConString="DRIVER={MySQLODBC3.51Driver};"+
- "SERVER=localhost;"+
- "DATABASE=inv;"+
- "UID=root;"+
- "PASSWORD=831025;"+
- "OPTION=3";
- OdbcConnectionMyConnection=newOdbcConnection(MyConString);
- MyConnection.Open();
- Console.WriteLine("\nsuccess,connectedsuccessfully!\n");
- stringquery="insertintotestvalues('hello','lucas','liu')";
- OdbcCommandcmd=newOdbcCommand(query,MyConnection);
- //处理异常:插入重复记录有异常
- try{
- cmd.ExecuteNonQuery();
- }
- catch(Exceptionex){
- Console.WriteLine("recordduplicate.");
- }
- finally{
- cmd.Dispose();
- }
- stringtmp1=null;
- stringtmp2=null;
- stringtmp3=null;
- query="select*fromtest";
- OdbcCommandcmd2=newOdbcCommand(query,MyConnection);
- OdbcDataReaderreader=cmd2.ExecuteReader();
- while(reader.Read()){
- tmp1=reader[0].ToString();
- tmp2=reader[1].ToString();
- tmp3=reader[2].ToString();
- }
- this.textBox1.Text=tmp1+""+tmp2+""+tmp3;
- stringMyConString="DRIVER={MySQLODBC3.51Driver};"+
- "SERVER=localhost;"+
- "DATABASE=inv;"+
- "UID=root;"+
- "PASSWORD=831025;"+
- "OPTION=3";
- OdbcConnectionMyConnection=newOdbcConnection(MyConString);
- OdbcDataAdapteroda=newOdbcDataAdapter("select*fromcustomer",MyConnection);
- DataSetds=newDataSet();
- oda.Fill(ds,"employee");
- this.dataGridView1.DataSource=ds.Tables["employee"];
- MyConnection.Close();
- }
- }
- }
【编辑推荐】