gpt4 book ai didi

c# - 将组合框中输入的数据与数据库进行匹配

转载 作者:行者123 更新时间:2023-11-30 01:37:54 25 4
gpt4 key购买 nike

这里我想通过使用离开事件函数来验证用户输入的数据,所以我在这里要做的就是匹配数据库中用户输入的数据。我在这里使用这段代码做到了这一点,但我不确定我做得是否正确。我尝试运行它,但它不起作用。

private void cboBranch_Leave(object sender, EventArgs e)
{

if (cboBranch.Text.Length > 0)
{
try
{
using (MySqlConnection con = new MySqlConnection(serverstring))
{
string query = "SELECT * FROM tblBranches WHERE branch_name=@branch";

con.Open();
using (MySqlCommand cmd = new MySqlCommand(query, con))
{
using (MySqlDataReader dr = cmd.ExecuteReader())
{
cmd.Parameters.Add("@branch", MySqlDbType.VarChar, 30).Value = cboBranch.Text;

int count = 0;
bool flag = false;

while (dr.Read())
{
count++;
if (count == 1)
{
flag = true;
}
}

if (flag == false)
{
MessageBox.Show("The Branch name you entered does not match.", "AFICIONADO", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
cboBranch.Select();
}
}

}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}

}
}

最佳答案

您可以使用SELECT COUNT(*)....从表中获取计数,此外您在将参数附加到命令之前正在执行命令。像这样的东西:

private void cboBranch_Leave(object sender, EventArgs e)
{
if (cboBranch.Text.Length > 0)
{
try
{
using (MySqlConnection con = new MySqlConnection(serverstring))
{
string query = "SELECT count(*) FROM tblBranches WHERE branch_name=@branch";
con.Open();
using (MySqlCommand cmd = new MySqlCommand(query, con))
{

cmd.Parameters.Add("@branch", MySqlDbType.VarChar, 30).Value = cboBranch.Text;

//Use ExecuteScalar
int count = Convert.ToInt32(cmd.ExecuteScalar());
if (count <= 0)
{
MessageBox.Show("The Branch name you entered does not match.", "AFICIONADO", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
cboBranch.Select();
}
}

}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}

}
}

关于c# - 将组合框中输入的数据与数据库进行匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16606681/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com