【发布时间】:2016-03-06 12:23:47
【问题描述】:
所以我目前对我的程序的逻辑感到困惑,我已经多次运行它但我不太确定。我基本上希望能够通知用户说他们输入的联系电话已经存在于数据库中。我已经接近了,我确信我已经做了很多研究,但我不认为我所做的实际上是检查数据库,而只是告诉它匹配文本框中的任何内容,而不是检查数据库。
只是为了澄清我不想从数据库中提取数据并将其放入文本框中。谢谢。
更新:针对两种不同建议解决方案的两种不同程序。
(可能的解决方案 1)更新的联系电话是使用 COUNT 的唯一方法:
private void CheckContactNumber()
{
string checkContactNum = "SELECT COUNT(*) FROM Employee WHERE ContactNumber = " + addContactNum.Text + " "; //01234567890
OleDbCommand cmd = new OleDbCommand(checkContactNum, conn);
conn.Open();
OleDbDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
int countDup = (int)dr[0];
if (countDup > 0 && addContactNum.Text != "")
{
err += "Contact number is already listed in the database\r\n";
errorContactNum.Visible = true;
uniqueContactNumber = false;
}
else if (countDup == 0 && addContactNum.Text != "")
{
errorContactNum.Visible = false;
uniqueContactNumber = true;
}
}
conn.Close();
}
(可能的解决方案 2)更新到建议的第二个解决方案:
if (err == "")
{
// you miss s here
string addEmployee = "if not exists(select LastName from Employee where LastName = @LastName)INSERT INTO Employee(FirstName, LastName, Role, DateOfHire, ContactNumber)" +"VALUES(@FirstName, @LastName, @Role, @DateOfHire, @ContactNumber)";
OleDbCommand cmd = new OleDbCommand(addEmployee, conn);
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
cmd.Parameters.Add("@FirstName", OleDbType.VarChar).Value = addFirstName.Text;
cmd.Parameters.Add("@LastName", OleDbType.VarChar).Value = addLastName.Text;
cmd.Parameters.Add("@Role", OleDbType.VarChar).Value = addRole.Text;
cmd.Parameters.Add("@DateOfHire", OleDbType.VarChar).Value = addDateOfHire.Text;
cmd.Parameters.Add("@ContactNumber", OleDbType.VarChar).Value = addContactNum.Text;
conn.Open();
// i removed the duplicated code
if (cmd.ExecuteNonQuery() != 1)
{
err += "Contact number is already listed in the database\r\n";
errorContactNum.Visible = true;
}
conn.Close();
addFirstName.Text = String.Empty;
addLastName.Text = String.Empty;
addRole.Text = String.Empty;
addContactNum.Text = String.Empty;
addRole.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
}
//Save It
else
{
MessageBox.Show(err);
}
}
Here is an Image of my database which is linked to my program.
【问题讨论】:
-
为什么不使用 select count(*) from employee where contact_number='022222' 之类的查询,其中“022222”是您想要的数字,如果 count 为 1,那么它已经存在,否则呢你想要的..
-
但这不是只对一个号码有效,因为您正在搜索一个特定的号码吗?我还在我的数据库中将 ContactNumber 设为字符串(短文本)。
-
联系号码是字符串还是数字都没有关系,如果您想搜索多个号码,那么为什么不将其用作 select count(*) from employee where contact_number=addContactNum.Text
-
@user6002727 我正在尝试使用它,但它说语法及其突出显示存在问题:OleDbDataReader dr = cmd.ExecuteReader();
-
你愿意分享你想要做什么吗?
标签: c# sql visual-studio