我遇到了有关标记重复数据的问题。在我的项目中,已经存在的记录不能记录两次。我关注了stackoverflow的多篇文章,并且知道我必须使用 executescalar 来执行此操作。.我使用了executescalar,但它无法处理现有数据。您能帮我解决一下吗?
这是我的代码部分:
{
appointmentdate = dtappointmentdate.Value;
today = DateTime.Now;
String prob = txtproblemdefination.Text;
String rec = "";
if (appointmentdate < today)
{
MessageBox.Show("Please Enter Correct Date.");
}
else
{
SqlCommand check_User_Name = new SqlCommand("SELECT count(*) FROM appointmentTable WHERE PatientName = '" + patientname + "'And (DoctorName = '" + docname + "'And AppointmentDateSet = '" + appointmentdate + "')", sqlCon);
check_User_Name.Parameters.AddWithValue("@patname", patientname);
check_User_Name.Parameters.AddWithValue("@docname", docname);
check_User_Name.Parameters.AddWithValue("@appointmentdate", appointmentdate);
if (sqlCon.State != ConnectionState.Open)
{
sqlCon.Open();
}
int UserExist = (Int32)check_User_Name.ExecuteScalar();
if (UserExist > 0)
{
MessageBox.Show("You can't make appointment twice a day. ");
}
else
{
SqlCommand insertCommand = new SqlCommand("insert into appointmentTable(PatientName,DoctorName,ClinicLocation,AppointmentDateSet,Problem,Recommendation) values(@docname, @patname, @doclocation, @appointmentdate,@prob,@rec)");
insertCommand.Parameters.AddWithValue("@patname", patientname);
insertCommand.Parameters.AddWithValue("@docname", docname);
insertCommand.Parameters.AddWithValue("@doclocation", doclocation);
insertCommand.Parameters.AddWithValue("@appointmentdate", appointmentdate);
insertCommand.Parameters.AddWithValue("@prob", prob);
insertCommand.Parameters.AddWithValue("@rec", rec);
int row = objdbaccess.executeQuery(insertCommand);
if (row == 1)
{
MessageBox.Show("Appointment is Successfully Done.");
}
else
{
MessageBox.Show("Error!Please try again later.");
}
sqlCon.Close();
}
}
答案 0 :(得分:1)
您应该将代码更改为:
我假设约会日期的类型为DateTime
,否则您可以从here中选择正确的类型
using(var check_User_Name= SqlCommand("SELECT count(*) FROM appointmentTable WHERE PatientName = @patname And DoctorName = @docname And AppointmentDateSet = @appointmentdate )", sqlCon)
{
check_User_Name.Parameters.Add("@patname", DbType.String).Value = patientname;
check_User_Name.Parameters.Add("@docname", DbType.String).Value = docname;
check_User_Name.Parameters.Add("@appointmentdate", DbType.DateTime).Value = appointmentdate;
con.Open();
int UserExist = (int)check_User_Name.ExecuteScalar();
// Followed by your code
}