usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel;usingSystem.Data;usingSystem.Drawing;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;usingSystem.Windows.Forms;usingMysql.data;usingMySql.Data.MySqlClient;namespacewindowsformsapplication1{ Public Partial classForm1:form {stringmyConnectionString ="server=localhost;uid=root;pwd=1234;database=student"; PublicForm1 () {InitializeComponent (); } //in each button or other action to add the database open, operation, close, so that the continuous independent operation; Private voidButton1_Click (Objectsender, EventArgs e) { intStudentscore; stringScore =TextBox3.Text; int. TryParse (Score, outStudentscore); Mysqlconnection Connection=Newmysqlconnection (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 { //Finally, close the operation; if(Connection. state==connectionstate.open) {connection. Close (); LoadData (); } } } Private voidLoadData () {mysqlconnection connection=Newmysqlconnection (myconnectionstring); Connection. Open (); Try{mysqlcommand cmd=connection. CreateCommand (); Cmd.commandtext="SELECT * from Student_score"; //The reading and writing of the database can be operated independently;Mysqldataadapter ADAP =Newmysqldataadapter (CMD); DataSet DS=NewDataSet (); Adap. Fill (DS); //indicates that the first data table in the DS is displayed, with the default setting (all displayed);Datagridview1.datasource = ds. tables[0]. DefaultView; } Catch(Exception) {Throw; } finally { if(Connection. state==connectionstate.open) {connection. Close (); } } } }}
Image:
C # and MySQL combat seven: Input parameters in the interface;