【问题标题】:VB.NET SQL Server Insert - ExecuteNonQuery: Connection property has not been initializedVB.NET SQL Server 插入 - ExecuteNonQuery:连接属性尚未初始化
【发布时间】:2023-04-04 13:49:01
【问题描述】:

在表单加载事件中,我连接到 SQL Server 数据库:

Private Sub AddBook_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            myConnection = New SqlConnection("server=.\SQLEXPRESS;uid=sa;pwd=123;database=CIEDC")
            myConnection.Open()

End Sub

在插入事件中,我使用以下代码:

Private Sub cmdAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdAdd.Click
            Try
                myConnection.Open()
                myCommand = New SqlCommand("INSERT INTO tblBook(BookCode, BookTitle, Author, PublishingYear, Price, EnterDate, CatID, RackID, Amount) VALUES('" & txtBookCode.Text & "','" & txtTitle.Text & "','" & txtAuthor.Text & "','" & txtPublishYear.Text & "','" & txtPrice.Text & "', #" & txtEnterDate.Text & "#, " & txtCategory.Text & "," & txtRack.Text & "," & txtAmount.Text & ")")
                myCommand.ExecuteNonQuery()
                MsgBox("The book named '" & txtTitle.Text & "' has been inseted successfully")
                ClearBox()
            Catch ex As Exception
                MsgBox(ex.Message())
            End Try
            myConnection.Close()
End Sub

它会产生以下错误:

ExecuteNonQuery: Connection property has not been initialized

【问题讨论】:

    标签: sql vb.net executenonquery


    【解决方案1】:
    1. 连接分配 - 您没有设置 SQLCommand 的连接属性。您可以在不添加任何代码的情况下执行此操作。 这是你的错误的原因。

      myCommand = New SqlCommand("INSERT INTO tblBook(BookCode, BookTitle, Author, PublishingYear, Price, EnterDate, CatID, RackID, Amount) VALUES('" & txtBookCode.Text & "','" & txtTitle.Text & "','" & txtAuthor.Text & "','" & txtPublishYear.Text & "','" & txtPrice.Text & "', #" & txtEnterDate.Text & "#, " & txtCategory.Text & "," & txtRack.Text & "," & txtAmount.Text & ")", MyConnection)
      
    2. 连接处理 - 您还需要从负载处理程序中删除“MyConnection.Open”。就像您当前所做的那样,只需在您的 Click Handler 中打开并关闭它。 这不是导致错误的原因。

    3. 参数化 SQL - 您需要使用 SQL 参数,尽管您没有使用存储过程。 这不是你的错误的原因。正如Conrad 提醒我的那样,您的原始代码将值直接从用户转储到 SQL 语句中。除非您使用 SQL 参数,否则恶意用户会窃取您的数据。

      Dim CMD As New SqlCommand("Select * from MyTable where BookID = @BookID")
      CMD.Parameters.Add("@BookID", SqlDbType.Int).Value = CInt(TXT_BookdID.Text)
      

    【讨论】:

    • 希望小鲍比桌不会创作任何最终出现在此数据库中的书籍
    • 您反对快速用户增强型数据库的概念吗?
    • 啊,它是一个功能而不是一个缺陷。不错!
    【解决方案2】:

    你需要在命令上设置Connection属性:

    myCommand.Connection = myConnection
    

    【讨论】:

      【解决方案3】:

      与错误消息的含义差不多 - SqlCommand 对象的 Connection 属性尚未分配给您打开的连接(在本例中,您将其称为 myConnection)。

      另外,这里有一点建议。对 sql 参数进行一些阅读 - 在没有任何完整性检查的情况下从用户输入进行 sql 连接是 SQL injection 攻击发生的方式。

      这是一种方法:

      Private Sub cmdAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdAdd.Click
          Try
              myConnection.Open()
              myCommand = New SqlCommand( _
              "INSERT INTO tblBook(BookCode, BookTitle, Author, PublishingYear, Price, " & _
              "                    EnterDate, CatID, RackID, Amount) " & _
              "VALUES(@bookCode, @bookTitle, @author, @publishingYear, @price, @enterDate, " & _
              "       @catId, @rackId, @amount)")
              myCommand.Connection = myConnection
              with myCommand.Parameters
                  .AddWithValue("bookCode", txtBookCode.Text)
                  .AddWithValue("bookTitle", txtTitle.Text)
                  .AddWithValue("author", txtAuthor.Text)
                  .AddWithValue("publishingYear", txtPublishYear.Text)
                  .AddWithValue("price", txtPrice.Text)
                  .AddWithValue("enterDate", txtEnterDate.Text)
                  .AddWithValue("catId", txtCategory.Text)
                  .AddWithValue("rackId", txtRack.Text)
                  .AddWithValue("amount", txtAmount.Text)
              end with
              myCommand.ExecuteNonQuery()
              MsgBox("The book named '" & txtTitle.Text & "' has been inseted successfully")
              ClearBox()
          Catch ex As Exception
              MsgBox(ex.Message())
          End Try
          myConnection.Close()
      End Sub
      

      【讨论】:

      • 我认为您需要在对 AddWithValue 的调用中将“@”添加到参数名称的前面
      • SqlCommand.Parameters 上 MSDN 页面底部的社区评论声称没有必要。我没有编译和测试上面的,所以,YMMV。
      • 我检查了,你说得对,你不需要添加“@”很好,我学到了一些新东西。 +1
      【解决方案4】:

      模块模块1 公共配置作为 System.Data.SqlClient.SqlConnection 公共 com 作为 System.Data.SqlClient.SqlCommand 公共 ds 作为 System.Data.SqlClient.SqlDataReader 将 sqlstr 调暗为字符串

      Public Sub main()
          con = New SqlConnection("Data Source=.....;Initial Catalog=.....;Integrated Security=True;")
          con.Open()
          frmopen.Show()
          'sqlstr = "select * from name1"
          'com = New SqlCommand(sqlstr, con)
          Try
              com.ExecuteNonQuery()
      
              'MsgBox("success", MsgBoxStyle.Information)
          Catch ex As Exception
              MsgBox(ex.Message())
          End Try
          'con.Close()
      
      
      
          'MsgBox("ok", MsgBoxStyle.Information, )
      
      End Sub
      

      结束模块

      【讨论】:

        【解决方案5】:

        请尝试将您的连接使用(包括打开)包装在 USING 块中。假设使用 web.config 作为连接字符串:

            Dim connection As New SqlConnection(ConfigurationManager.ConnectionStrings("web.config_connectionstring").ConnectionString)
            Dim query As New String = "select * from Table1"
            Dim command as New SqlCommand(query, connection)
        
        Using connection
           connection.Open()
           command.ExecuteNonQuery()
        End Using
        

        并且参数化用户输入的任何内容..拜托!

        【讨论】:

          猜你喜欢
          • 2013-01-15
          • 2012-05-03
          • 2011-07-22
          • 2012-08-20
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多