通过MySql connector net组件操作MYSQL数据库:
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; using MySql.Data.MySqlClient; namespace DatabaseWindowsApp1 { public partial class Form1 : Form { private static string DB_CON_STR = "server=localhost;uid=root;pwd=root;database=test"; public Form1() { InitializeComponent(); } private void bindListView() { listView1.Clear(); listView1.Columns.Add("ID"); listView1.Columns.Add("Student"); MySqlConnection con = new MySqlConnection(DB_CON_STR); con.Open(); MySqlCommand cmd = new MySqlCommand("student"); cmd.Connection = con; cmd.CommandType = CommandType.TableDirect; MySqlDataReader dr = cmd.ExecuteReader(CommandBehavior.Default); while (dr.Read()) { System.Console.WriteLine(dr.GetInt32(0).ToString() + ": " + dr.GetString(1)); // Create three items and three sets of subitems for each item. ListViewItem item1 = new ListViewItem(dr.GetInt32(0).ToString()); // Place a check mark next to the item. item1.Checked = true; item1.SubItems.Add(dr.GetString(1)); //Add the items to the ListView. listView1.Items.Add(item1); } dr.Close(); con.Close(); } private void Form1_Load(object sender, EventArgs e) { bindListView(); } private void button1_Click(object sender, EventArgs e) { MySqlConnection con = new MySqlConnection(DB_CON_STR); con.Open(); MySqlCommand cmd = new MySqlCommand("INSERT INTO student (name) value (@name)"); cmd.Connection = con; cmd.Prepare(); cmd.Parameters.AddWithValue("@name", textBox1.Text); int i = cmd.ExecuteNonQuery(); if (i > 0) MessageBox.Show("插入记录成功"); bindListView(); } } }数据库结构:
mysql> describe class; +-------+-------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-------+-------------+------+-----+---------+----------------+ | sid | int(11) | NO | PRI | NULL | auto_increment | | name | varchar(32) | YES | | NULL | | +-------+-------------+------+-----+---------+----------------+ mysql> describe student; +-------+-------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-------+-------------+------+-----+---------+----------------+ | sid | int(32) | NO | PRI | NULL | auto_increment | | name | varchar(32) | YES | | NULL | | +-------+-------------+------+-----+---------+----------------+