我创建了一个简单的asp.net表单,它允许用户查看培训的日期列表并注册该日期,他们手动输入他们的名称和employeeid(我不想让dulpicate雇工IDS),所以我需要弄清楚如何检查在C#..在插入sql数据库之前检查现有记录
代码:
public string GetConnectionString()
{
//sets the connection string from your web config file "ConnString" is the name of your Connection String
return System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
}
private void checkContraint()
{
SqlConnection conn = new SqlConnection(GetConnectionString());
string sql = "Select "; //NEED HELP HERE
}
private void InsertInfo()
{
var dateSelected = dpDate.SelectedItem.Value;
SqlConnection conn = new SqlConnection(GetConnectionString());
string sql = "INSERT INTO personTraining (name,department,title,employeeid,training_id, training,trainingDate,trainingHour, trainingSession)SELECT @Val1b+','[email protected],@Val2,@Val3,@Val4,training_id,training,trainingDate,trainingHour,trainingSession FROM tbl_training WHERE training_id [email protected]_id ";
try
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("@Val1", txtName.Text);
cmd.Parameters.AddWithValue("@Val1b", txtLname.Text);
cmd.Parameters.AddWithValue("@Val2", txtDept.Text);
cmd.Parameters.AddWithValue("@Val3", txtTitle.Text);
cmd.Parameters.AddWithValue("@Val4", txtEmployeeID.Text);
//Parameter to pass for the select statement
cmd.Parameters.AddWithValue("@training_id", dateSelected);
cmd.CommandType = CommandType.Text;
//cmd.ExecuteNonQuery();
int rowsAffected = cmd.ExecuteNonQuery();
if (rowsAffected == 1)
{
//Success notification // Sends user to redirect page
Response.Redirect(Button1.CommandArgument.ToString());
ClearForm();
}
else
{
//Error notification
}
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
conn.Close();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
checkContraint();
InsertInfo();
您是否需要将其限制为每个员工ID的一个培训课程?或者每个日期一个,每个会话一个,等等? –
只需在整个表格中限制一个员工ID(唯一) – user959443
Royi的答案看起来就是这样。虽然不是检查约束方法的单独验证查询,但它应该在InsertInfo中打到错误通知处理程序。 –