sql命令返回布尔值以便在C#中进行处理

时间:2018-02-20 11:55:16

标签: c# sql database ado.net sqlcommand

是否可以从sql命令返回一个布尔值 - 然后使用它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();

}

这样做会在WHERE

中的SqlCommand附近给出语法错误

3 个答案:

答案 0 :(得分:2)

尝试使用有效的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;

 }

答案 1 :(得分:1)

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

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

答案 2 :(得分:1)

只需使用

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

并像这样调用SqlCommand

object o = cmd.ExecuteScalar();

您可以将bool设置为:

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