gpt4 book ai didi

c# - 返回 bool 值以在 C# 中处理的 sql 命令

转载 作者:搜寻专家 更新时间:2023-10-30 21:49:20 25 4
gpt4 key购买 nike

是否可以从 sql 命令返回一个 bool 值 - 然后在 C# 中使用它?

我目前有一个数据库,我在其中插入条目。我想在插入之前知道该条目是否存在,如果存在则做某事......

private void create_user_Click(object sender, EventArgs e)
{
int exist;
using (DbConnection connection = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\toilet\source\repos\WindowsFormsApp2\WindowsFormsApp1\Database1.mdf;Integrated Security=True"))
{
connection.Open();
using (DbCommand command = new SqlCommand("WHERE EXIST (SELECT id FROM [information] WHERE id == @given_id)"))
{
command.Parameters.Add(new SqlParameter("@given_id", create_user_username_textbox.Text));
command.Connection = connection;
exist = command.ExecuteNonQuery();
}
MessageBox.Show(Convert.ToString(exist));
}

//login_screen login = new login_screen();
//this.Hide();
//login.ShowDialog();
//this.Close();

}

这样做会在 SqlCommand

中的 WHERE 附近出现语法错误

最佳答案

尝试使用有效的 sql 语句并使用 ExecuteScalar 获取一些值以比较它是否存在。例如:

 using (DbCommand command = new SqlCommand("SELECT 1 FROM [information] WHERE id = @given_id"))
{
command.Parameters.Add(new SqlParameter("@given_id", create_user_username_textbox.Text));
command.Connection = connection;

// get the result from the sql statement
var result = command.ExecuteScalar();

// if the result is not null, convert it to an integer and compare it. Otherwise it is false (no records).
exists = result != null ? (int) result > 0 : false;

}

关于c# - 返回 bool 值以在 C# 中处理的 sql 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48884757/

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