using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; //引入MySQL using MySql.Data.MySqlClient; using System.Data.SqlClient; using System.Data.OleDb; namespace c_01_连接查询MySQL数据库 { public partial class frmQuery : Form { public frmQuery() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { MySqlConnection sqlCnn = new MySqlConnection(); sqlCnn.ConnectionString = "server = '127.0.0.1'; uid = 'root'; pwd = 'root'; database = 'ajax_stydy';";//连接字符串 MySqlCommand sqlCmd = new MySqlCommand(); sqlCmd.Connection = sqlCnn; sqlCmd.CommandText = "select * from user"; try { sqlCnn.Open(); MySqlDataReader rec = sqlCmd.ExecuteReader(); textBox2.AppendText("数据库连接成功! "); textBox1.AppendText(string.Format("ID 用户名 密码 ")); while (rec.Read()) { textBox1.AppendText(string.Format("{0} {1} {2} ", rec.GetInt32(0), rec.GetString(1), rec.GetString(2))); } textBox2.AppendText("读取数据完成! "); } catch (Exception ex) { MessageBox.Show(ex.Message, "error"); } finally { textBox2.AppendText("数据库连接关闭!"); sqlCnn.Close(); } } } }
数据库字段: