Test environment: Windows XP + MySql 5.0.24 + Visual C #2008 Exdivss Edition
By lucas 2008.12.29
1. Use MySQLDriverCS to connect to the MySQL database
Download and install MySQLDriverCS first. Address:
Http://sourceforge.net/projects/mysqldrivercs/
Find MySQLDriver. dll in the installation folder, and add the MySQLDriver. dll to the project.
Note: the version I downloaded is a 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. Access the mysql database through ODBC:
Reference: http://www.microsoft.com/china/community/Column/63.mspx
1. Install Microsoft ODBC.net: I installed a mysql-connector-odbc-3.51.22-win32.msi
2. Install MDAC 2.7 or later: the mdac_typ.exe 2.7 Simplified Chinese version is installed.
3. Install MySQL ODBC driver: I installed odbc_net.msi
4. Management Tools-> data source ODBC-> Configure DSN...
5. add reference to Microsoft. Data. Odbc. dll (1.0.3300) in solution management)
6. Add using Microsoft. Data. Odbc to the code;
Using System;
Using System. Collections. Generic;
Using System. ComponentModel;
Using System. Drawing;
Using System. Linq; // vs2005 does not seem to have this namespace. in c #2008, The automatically generated
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 ("success, connected successfully! ");
String query = "insert into test values (hello, lucas, liu )";
OdbcCommand cmd = new OdbcCommand (query, MyConnection );
// Handling exception: An error occurred while inserting duplicate records.
Try {
Cmd. ExecuteNonQuery ();
}
Catch (Exception ex ){
Console. WriteLine ("record duplicate .");
} Finally {
Cmd. Dispose ();
}
// ************************* Read