简体   繁体   English

VB.NET SQL Server插入 - ExecuteNonQuery:尚未初始化Connection属性

[英]VB.NET SQL Server Insert - ExecuteNonQuery: Connection property has not been initialized

In the form load event, I connect to the SQL Server database: 在表单加载事件中,我连接到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

Here in the Insert event, I use the following code: 在Insert事件中,我使用以下代码:

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

And It produces the following error: 它会产生以下错误:

ExecuteNonQuery: Connection property has not been initialized
  1. Connection Assignment - You aren't setting the connection property of the SQLCommand. 连接分配 - 您没有设置SQLCommand的连接属性。 You can do this without adding a line of code. 您可以在不添加代码行的情况下执行此操作。 This is the cause of your error. 这是导致错误的原因。

     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. Connection Handling - You also need to remove `MyConnection.Open' from your Load Handler. 连接处理 - 您还需要从加载处理程序中删除“MyConnection.Open”。 Just open it and close it in your Click Handler, as you are currently doing. 只需打开它并在您的Click Handler中关闭它,就像您目前正在做的那样。 This is not causing the error. 这不会导致错误。

  3. Parameterized SQL - You need to utilize SQL Parameters, despite the fact that you are not using a Stored Procedure. 参数化SQL - 您需要使用SQL参数,尽管您没有使用存储过程。 This is not the cause of your error . 这不是您的错误的原因 As Conrad reminded me, your original code dumps values straight from the user into a SQL Statement. 正如Conrad提醒我的那样,您的原始代码会将值直接从用户转储到SQL语句中。 Malicious users will steal your data unless you use SQL Parameters. 除非您使用SQL参数,否则恶意用户将窃取您的数据。

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

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

myCommand.Connection = myConnection

Pretty much what the error message implies - the Connection property of the SqlCommand object hasn't been assigned to the connection you opened (in this case you called it myConnection ). 几乎是错误消息所暗示的 - SqlCommand对象的Connection属性尚未分配给您打开的连接(在本例中,您将其称为myConnection )。

Also, a word of advice here. 另外,这里有一个建议。 Do some reading on sql parameters - doing sql concatenation from user input without any sanity checks is the way SQL injection attacks happen. 对sql参数进行一些阅读 - 在没有任何健全性检查的情况下从用户输入执行sql连接是SQL注入攻击发生的方式。

This is one way to do it: 这是一种方法:

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

Module Module1 Public con As System.Data.SqlClient.SqlConnection Public com As System.Data.SqlClient.SqlCommand Public ds As System.Data.SqlClient.SqlDataReader Dim sqlstr As String Module Module1 Public con As System.Data.SqlClient.SqlConnection Public com As System.Data.SqlClient.SqlCommand Public ds As System.Data.SqlClient.SqlDataReader Dim sqlstr As String

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

End Module 结束模块

Please try to wrap the use of your connections (including just opening) inside a USING block. 请尝试在USING块中包含您的连接(包括刚刚打开)的使用。 Assuming the use of web.config for connection strings: 假设使用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

And PARAMETERIZE anything user-entered.. please! 和PARAMETERIZE用户输入的任何东西..请!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 VB.NET和SQL:ConnectionString属性尚未初始化 - VB.NET & SQL : The ConnectionString property has not been initialized C# SQL 查询 - ExecuteNonQuery:连接属性尚未初始化 - C# SQL Query - ExecuteNonQuery: Connection property has not been initialized 'ExecuteNonQuery:连接属性尚未初始化。' - 'ExecuteNonQuery: Connection property has not been initialized.' ExecuteNonQuery:连接属性尚未初始化 - ExecuteNonQuery: Connection property has not been initialized ConnectionString属性尚未初始化。 VB.Net - The ConnectionString property has not been initialized. VB.Net ExecuteNonQuery:尚未使用 Visual Studio 15 初始化连接属性 - ExecuteNonQuery: Connection property has not been initialized using visual studio 15 如何解决“ ExecuteNonQuery:连接属性尚未初始化?”的错误? - how to solve error of “ ExecuteNonQuery: Connection property has not been initialized?” C# 数据库插入 (ASP.NET) - ExecuteNonQuery:CommandText 属性尚未初始化 - C# Database Insert (ASP.NET) - ExecuteNonQuery: CommandText property has not been initialized SQL Server 错误:连接字符串属性尚未初始化 - SQL Server error: connection string property has not been initialized VB.net 执行 SQL 服务器 ExecuteNonQuery 崩溃 - VB.net execute SQL Server ExecuteNonQuery crash
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM