【发布时间】:2019-12-23 09:42:30
【问题描述】:
我遇到了一个关于标记重复数据的问题。在我的项目中,已经存在的记录不能记录两次。我已经关注了 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();
}
}
【问题讨论】:
-
您正在使用参数化查询,这很好,但在第一个查询中,您连接变量并使用参数
-
您没有在 SELECT 查询中使用命令参数,并且使用
DateTime检查完全等价是不可能的。AppointmentDateSet是什么数据类型?您应该使用Parameters.Add(),指定匹配的数据类型。 -
@Jimi..如何在选择查询中使用命令参数..你能帮帮我吗?
-
执行标量只有一列。您必须使用返回整数的 ExecuteNonQuery。如果整数值为零,则行已经存在。因此,您需要创建一个 UpdateCommand 来更新现有行。
-
@jdweng int UserExist = (Int32)check_User_Name.ExecuteNonQuery(); if (UserExist == 0) { MessageBox.Show("一天不能预约两次。"); }