sql 命令返回用于在 C# 中处理的布尔值

sql command returning boolean for processing in C#

是否可以从 sql 命令中 return 布尔值 - 然后使用 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;

 }

使用以下查询检查可用性。

IF EXIST (SELECT id FROM [information] WHERE id = @given_id) 
SELECT CAST(1 AS BIT)
ELSE 
SELECT CAST(0 AS BIT)

只需使用

SELECT id FROM [information] WHERE id == @given_id

并这样调用 SqlCommand

object o = cmd.ExecuteScalar();

您可以像这样设置布尔值:

bool valueExists = o != null && o != DBNull.Value;