Description: The previous article wrote updated data, followed by the addition and deletion of data.
Add a record
From the programmer's point of view, adding a new record to a database is no different from changing an existing record.
Create a Command object for the SQL INSERT command or stored procedure (add parameters to the Command object, if necessary),
Then execute it.
For example, if you want to add a new student record to the student table, use the following code example:
Private voidbtnAdd_Click (Objectsender, EventArgs e) { stringConnectionString ="Data source= (local); Initial catalog=student;integrated Security=sspi"; //Stitching Command String stringInsertQuery ="Insert studentinfo (id,sname,sgrade,ssex,semail,sphone,saddress)"+"values (' 2007001001 ', ' Xiao Zhang ', ' 2007106 ', ' Male ', ' [email protected] ',"+"' 18888888000 ', ' Chengdu Jinniu District ')"; //New ConnectionSqlConnection conn =NewSqlConnection (connectionString); //new Command ObjectSqlCommand cmd =NewSqlCommand (InsertQuery, conn); Conn. Open (); //Save Execution Results intRecordsAffected =cmd. ExecuteNonQuery (); Conn. Close (); }
If the corresponding field in the database is identified, you do not need to add data by means of the program, in fact, this will cause the operation to fail.
For example
When you add new information to a curriculum, you do not need or allow data to be added to the ID.
The data in the ID is automatically maintained by the database system.
Deleting records
Deleting records is very similar to updating data using commands.
Here is a sample code to delete a student record:
Private voidBtndel_click (Objectsender, EventArgs e) { stringConnectionString ="Data source= (local); Initial catalog=student;integrated Security=sspi"; //Stitching Command String stringDeletetquery ="Delete from Studentinfo where id= ' 2007001001 '"; //New ConnectionSqlConnection conn =NewSqlConnection (connectionString); //new Command ObjectSqlCommand cmd =NewSqlCommand (Deletetquery, conn); Conn. Open (); //Save Execution Results intRecordsAffected =cmd. ExecuteNonQuery (); Conn. Close (); }
C # and Database Access technical Summary (10) Add & Delete