Use the MySql connector net component to operate the MYSQL database:
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 button#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 ("successful insertion record ");
BindListView ();
}
}
}
Database Structure:
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 |
+ ------- + ------------- + ------ + ----- + --------- + ---------------- +
From the column of michaelpp