如何检查行是否存在?

7
这是我用来显示/搜索数据库表中记录的代码。如何添加验证,以确定记录是否存在?它是通过会员ID进行搜索的。如果记录不存在,应该如何显示消息?
 string connectionstring = "Server=Momal-PC\\MOMAL;Database=Project;Trusted_Connection=True;";
 SqlConnection conn = new SqlConnection();
 conn.ConnectionString = connectionstring;
 conn.Open();


  SqlDataAdapter sda = new SqlDataAdapter("Select * from Members where Number = '" + SearchID.Text + "'", conn);
  DataTable dtStock = new DataTable();

  sda.Fill(dtStock);
  dataGridView1.DataSource = dtStock;

  conn.Close();
6个回答

7
if( 0 == dtStock.Rows.Count ) // does not exist

3

你可以像这样使用:

If(dtStock.Rows.Count > 0) // If dtStock.Rows.Count == 0 then there is no rows exists.
{
    // Your Logic
}

请看这里这里。如何使用DatasetDataTables。

2
你可以使用 DataRowCollection.Count 属性。

获取此集合中 DataRow 对象的总数。

If(0 == dtStock.Rows.Count)
  Console.WriteLine("There are no rows in that datatable")

2
你可以像这样做
    If(dtStock.Rows.Count > 0) 
    {
    //code goes here
    dataGridView1.DataSource = dtStock;
    }
    else
    {
    //Record not exists
    }

2

这个 SQL 查询语句可能会更快,因为它只返回 0 或 1 行匹配的结果给客户端,而不是每一行和每一列的所有匹配结果。请不要再习惯使用 *。

SELECT  1 As X WHERE EXISTS (
    Select 1 from Members where Number = '" + SearchID.Text + "')"

好的,我会做到。谢谢。 - momal

1
 public static int RowCount()
        {

            string sqlConnectionString = @" Your connection string";
            SqlConnection con = new SqlConnection(sqlConnectionString);
            con.Open();
            SqlCommand cmd = new SqlCommand("SELECT COUNT(*) AS Expr1 FROM Tablename", con);
            int result = ((int)cmd.ExecuteScalar());
            con.Close();
            return result;
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接