【问题标题】:Check if a row exists using windows form?使用windows窗体检查是否存在一行?
【发布时间】:2019-12-19 21:00:39
【问题描述】:

我正在创建一个约会表,我想在另一个用户进入之前检查该行是否包含相同的 Date、Slot、HR。

在显示的代码之前打开连接。

SqlCommand slot_check = new SqlCommand("select * from Appointment where AppoinmentDate='"+textBox1.Text+"' and Slot='"+comboBox3.Text+ "'and HRName='" +comboBox2.Text+"'");

SqlDataReader Exist = slot_check.ExecuteReader(); 

if (Exist.HasRows)
                {
                    string message = "Appointment Already Exists!!!!!";
                    MessageBox.Show(message);
                }
                else
                {
                    string message = "Update";
                    MessageBox.Show(message);
                }

System.InvalidOperationException: 'ExecuteReader: 连接属性尚未初始化。'

【问题讨论】:

  • SqlCommand中的连接在哪里设置?如果没有连接,您的命令将无法访问数据库并执行。旁注:尽快了解如何使用参数化查询而不是连接字符串
  • Little Bobby Tables sez:请在查询中使用参数!!
  • 如果您稍后要获取约会数据,您可以将if (Exist.HasRows) 更改为if (Exist.Read()).Read() 函数如果确实读取了 false,则返回 true,如果没有(如果不存在数据或所有数据都已读取)

标签: c# sql .net windows winforms


【解决方案1】:

要执行一个命令,两个信息是必不可少的:
要执行的 sql 字符串和到达数据库的连接。

如果没有连接,您的命令将无法执行,因为框架不知道如何读取或写入数据库。

SqlCommand 构造函数有一个重载,它接受两个必需的参数:

SqlCommand cmd = new SqlCommand(sqlText, connectionInstance);

所以你的代码应该是这样的

// The command text to run, without string concatenations and with parameters placeholders
string sqlText = @"select * from Appointment 
                   where AppoinmentDate=@aptDate 
                     and Slot=@slot 
                     and HRName=@name";

// Using statement to correctly close and dispose the disposable objects
using(SqlConnection cnn = new SqlConnection(connectionString))
using(SqlCommand slot_check = new SqlCommand(sqlText, cnn))
{
     // A parameter for each placeholder with the proper datatype
     cmd.Parameters.Add("@aptDate", SqlDbType.Date).Value = Convert.ToDateTime(textBox1.Text);
     cmd.Parameters.Add("@slot", SqlDbType.NVarChar).Value = comboBox3.Text;
     cmd.Parameters.Add("@name", SqlDbType.NVarChar).Value = comboBox2.Text;
     cnn.Open();         
     // Even the SqlDataReader is a disposable object
     using(SqlDataReader Exist = slot_check.ExecuteReader())
     {
         if (Exist.HasRows)
         {
              string message = "Appointment Already Exists!!!!!";
              MessageBox.Show(message + " " + Exist + comboBox2.Text);
         }
         else
         {
              string message = "Update";
              MessageBox.Show(message);
         }
    }
}

如您所见,代码现在有一个传递给命令构造函数的连接和一个没有连接字符串但使用参数构建的命令文本。
对于任何类型的数据库相关操作,使用参数都是一种强制方法。如果没有参数,您的代码可能会被众所周知的 Sql Injection hack 所利用,而且,在您的值中简单地存在单引号可能会破坏 sql 语法,从而导致语法错误异常

请注意,此代码仍然可能是错误的,因为我不知道您的表中 WHERE 语句中使用的列中存储了哪种数据。我假设了某种类型,但您应该检查您的表格并验证它们是否正确。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-11
    • 1970-01-01
    • 2018-11-06
    • 2017-09-11
    • 1970-01-01
    • 2012-11-09
    相关资源
    最近更新 更多