PRIMARY KEY violation, system about ' pk_t2 ': オブジェクト ' T2 ' には duplicate したキーは 挿 into できません. /r/nステートメントは finally されました. <?xml:namespace prefix = o ns = "Urn:schemas-microsoft-com:office:office"/>
Analysis: The above problem is that when inserting into the table T2, the primary key is inserted repeatedly. Because a table may have 1 or more primary keys, the tables in the database are unique to the primary key, regardless of the number.
①
First set up a student table, Sno primary key
CREATE TABLE Student_info
(
SNO INT CONSTRAINT S1 PRIMARY KEY,
Sname CHAR (6) CONSTRAINT S2 not NULL,
SEX CHAR (2) CONSTRAINT S3 CHECK (SEX in (' 0 ', ' 1 ')),
Birthday DATETIME
)
② inserts 3 data into the table
INSERT into Student_info
SELECT 1, ' TOM ', ' 1 ', ' 1983/04/15 '
UNION All
SELECT 2, ' Herry ', ' 0 ', ' 1983/04/16 '
UNION All
SELECT 3, ' JIM ', ' 1 ', ' 2008/10/17 '
③ If we use the frequently used SQL to once again insert this message that the name is Tom.
Insert into Student_info (sno,sname,sex,birthday)
Values (1, ' TOM ', ' 1 ', ' 1983/04/15 ')
There will be the mistakes we have mentioned above. That is, the primary key repeats cannot be inserted repeatedly.
④ instead of the third step of SQL, we add a row to the dataset table in the form of the program code, assigning the newly added row to the Tom information, and then updating it back to the database using the Update method. See what happens.
String strconn= "Data source=.;i Nitial catalog=test; User Id=sa; Password= ";
SqlConnection conn=new SqlConnection (strconn);
SqlCommand cmd=new SqlCommand ("SELECT * from Student_info", conn);
SqlDataAdapter SDA = new SqlDataAdapter (cmd);
Automatically generate commands for dataset updates
SqlCommandBuilder cb=new SqlCommandBuilder (SDA);
Populating data sets
DataSet Public_ds =new DataSet ();
Sda. Fill (Public_ds, "student_info");
Modify the DataSet-insert Tom's information here again
DataRow Drrow = Public_ds. Tables[0]. NewRow ();
drrow["SNO"]=1;
drrow["sname"]= "TOM";
drrow["SEX"]= "1";
drrow["Birthday"]= "1983/04/15";
Public_ds. Tables[0]. Rows. ADD (Drrow);
Updating a database with a changed dataset
Sda. Update (Public_ds, "student_info");