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(); } } } |
|