-1
我正试图插入到SQL Server数据库中。我有一个四列的表,主键是三列的组合<name, coursename, semester>
。SQL Server异常组合主键
我想在此表中插入一条记录,并且我希望该程序在插入副本时给我一个错误。但是,当我插入但没有插入记录时,不会发出错误。
有人可以告诉我与我的代码问题?谢谢
这里是我的代码部分:
try
{
string semester1 = semester.Text + syear.Text + "-" + eyear.Text;
SqlConnection conn = new SqlConnection("Data Source=SOURAYA-PC\\SQLEXPRESS; Initial Catalog=transcripts;Integrated Security=True");
SqlCommand command3 = new SqlCommand("insert into courses(name, coursename, semester, grade) values('" + DropDownList1.SelectedItem.Text + "','" + course_name.Text + "','" + semester1 + "',"+grades.Text+"')", conn);
conn.Open();
command3.ExecuteNonQuery();
}
catch (SqlException s)
{
if (s.Number == 2627)
{
error.Text = "Record already exists";
}
}
[SQL注入警报](http://msdn.microsoft.com/en-us/library/ms161953%28v=sql.105%29.aspx) - 你应该**不**连接一起使用你的SQL语句 - 使用**参数化查询**来代替以避免SQL注入 –
marc_s表示的内容,并且:错误文本仅在s.Number'等于2627时设置,其他情况下为SqlException' , 什么都没发生。 – Stephen
谢谢,我将改变现在:) – smn14