using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms;using MySql.Data;using MySql.Data.MySqlClient;namespace WindowsFormsApplication1{ public partial class Form1 : Form { string MyConnectionString = "server=localhost;uid=root;pwd=1234;database=student"; public Form1() { InitializeComponent(); } //在每个按钮或其他动作里面添加数据库的打开、操作、关闭;这样可以连续不断的独立的运行; private void button1_Click(object sender, EventArgs e) { int studentScore; string score = textBox3.Text; int.TryParse(score, out studentScore); MySqlConnection connection = new MySqlConnection(MyConnectionString); MySqlCommand cmd; connection.Open(); try { cmd = connection.CreateCommand(); cmd.CommandText = "INSERT INTO student_score(Id,Name,Score) VALUES(@Id,@Name,@Score)"; cmd.Parameters.AddWithValue("@Id", int.Parse(textBox1.Text)); cmd.Parameters.AddWithValue("@Name", textBox2.Text); cmd.Parameters.AddWithValue("@Score", studentScore); cmd.ExecuteNonQuery(); } catch(Exception) { throw; } finally { //最后是关闭操作; if(connection.State==ConnectionState.Open) { connection.Close(); LoadData(); } } } private void LoadData() { MySqlConnection connection = new MySqlConnection(MyConnectionString); connection.Open(); try { MySqlCommand cmd = connection.CreateCommand(); cmd.CommandText = "SELECT * FROM student_score"; //对数据库的读出和写入可以单独操作; MySqlDataAdapter adap = new MySqlDataAdapter(cmd); DataSet ds = new DataSet(); adap.Fill(ds); //表示显示ds中第一个数据表,默认设置(全部显示); dataGridView1.DataSource = ds.Tables[0].DefaultView; } catch (Exception) { throw; } finally { if(connection.State==ConnectionState.Open) { connection.Close(); } } } }}
图像: