【问题标题】:How do I check if row exists or not?如何检查行是否存在?
【发布时间】:2013-04-19 05:15:58
【问题描述】:

这是我在数据库表中显示/搜索记录的代码。如何验证 roecord 是否存在?它正在搜索成员的 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();

【问题讨论】:

    标签: c# sql-server database


    【解决方案1】:
    if( 0 == dtStock.Rows.Count ) // does not exist
    

    【讨论】:

      【解决方案2】:

      你可以这样使用:

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

      HereHere。如何使用DatasetDataTables.

      【讨论】:

        【解决方案3】:

        您可以使用DataRowCollection.Count 属性。

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

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

        【讨论】:

          【解决方案4】:

          你可以这样做

              If(dtStock.Rows.Count > 0) 
              {
              //code goes here
              dataGridView1.DataSource = dtStock;
              }
              else
              {
              //Record not exists
              }
          

          【讨论】:

            【解决方案5】:

            此 SQL 可能会快得多,因为它只会向客户端返回 0 或 1 行,而不是每个匹配的行和每一列。改掉使用*的习惯

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

            【讨论】:

            • 好的。我会这样做。谢谢。
            【解决方案6】:
             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;
                }
            

            【讨论】:

              猜你喜欢
              • 2018-12-10
              • 1970-01-01
              • 1970-01-01
              • 2016-12-05
              • 2014-10-02
              • 1970-01-01
              • 1970-01-01
              • 2014-05-14
              • 2011-08-23
              相关资源
              最近更新 更多