Using system;
Using system. Collections. Generic;
Using system. LINQ;
Using system. text;
Using system. Data. sqlclient;
Using system. Data;
Namespace ADO. net. addnewrow2
{
Class Program
{
Static void main (string [] ARGs)
{
/// <Summary>
/// Check whether the same data exists when adding data. If yes, a prompt is displayed and data insertion is canceled.
/// </Summary>
Sqlconnection CNN = new sqlconnection (@ "Server = michaelyang \ sqlexpress; Integrated Security = true;" + "database = northwinden"); // create a connection object using a link string
Sqldataadapter adapter = new sqldataadapter ("select customerid, companyName from customers", CNN); // create a sqldataadapter object
Sqlcommandbuilder builder = new sqlcommandbuilder (adapter); // The sqldataadapter object is passed as a parameter to the sqlcommandbuilder constructor to help us generate the updated SQL
Adapter. updatecommand = builder. getupdatecommand (); // assign the SQL generated by sqlcommandbuilder TO THE sqldataadapter object. When the update method is called, the data is synchronized.
Dataset DS = new dataset (); // create a dataset Method for filling in Data
Adapter. missingschemaaction = missingschemaaction. addwithkey; // tells ADO. Net to load the primary key information displayed through the missingschemaaction attribute of the dataadapter object
Adapter. Fill (DS, "MERs"); // fill in data
Console. writeline ("# Rows before change: {0}", DS. Tables ["MERs"]. Rows. Count); // read the total number of rows of the filled datatable data
Datarow findrow = Ds. Tables ["MERs"]. Rows. Find ("fuck"); // create a datarow object findrow to obtain the result
// Determine whether the result of findrow returned by the datarow object is true. Otherwise, the modification will be abandoned.
If (findrow = NULL)
{
Console. writeline ("fuck not find, will add to mers MERs table ");
Datarow ROW = Ds. Tables ["MERs"]. newrow (); // If the queried primary key ID does not exist, a new row object row is created.
Row ["customerid"] = "fuck"; // value assignment
Row ["companyName"] = "clochase. Inc."; // value assignment
DS. Tables ["MERs"]. Rows. Add (ROW); // use the add () method of the rows set to add a new row.
If (findrow! = NULL)
{< br> console. writeline ("Fuck successfully added to mers MERs table");
}< br> else
{< br> console. writeline ("fuck already present in database. ");
}
Adapter. Update (DS, "MERs ");
Console. writeline ("# Rows after change: {0}", DS. tables ["MERs"]. rows. count); // when updated to the database, query the total number of rows again to check whether the update is successful.
CNN. Close ();
Console. readkey ();
}
}
}
// Key points:
// The missingsechamaction attribute of the sqldataadapter object explicitly tells ADO. Net to load the primary key information, and before the dataset (Data filling) Operation