Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/73.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
VB.NET SQL Server插入-ExecuteOnQuery:尚未初始化连接属性_Sql_Vb.net_Executenonquery - Fatal编程技术网

VB.NET SQL Server插入-ExecuteOnQuery:尚未初始化连接属性

VB.NET SQL Server插入-ExecuteOnQuery:尚未初始化连接属性,sql,vb.net,executenonquery,Sql,Vb.net,Executenonquery,在form load事件中,我连接到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") my

在form load事件中,我连接到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
在这里的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
它会产生以下错误:

ExecuteNonQuery: Connection property has not been initialized
您需要在命令上设置属性:

myCommand.Connection = myConnection
  • 连接分配-您没有设置SQLCommand的连接属性。您无需添加一行代码即可完成此操作。这就是你犯错误的原因

  • 连接处理-您还需要从加载处理程序中删除'MyConnection.Open'。只需在单击处理程序中打开并关闭它,就像您当前所做的那样。这不是导致错误的原因

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

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

  • 与错误消息所暗示的差不多-SqlCommand对象的Connection属性尚未分配给您打开的连接(在本例中,您称之为
    myConnection

    还有,这里有一点建议。阅读一些sql参数-从用户输入进行sql连接而不进行任何健全性检查是攻击发生的方式

    这是一种方法:

    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
    
    模块1 Public con As System.Data.SqlClient.SqlConnection Public com As System.Data.SqlClient.SqlCommand 公共ds作为System.Data.SqlClient.SqlDataReader 作为字符串的Dim 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
    

    结束模块

    请尝试将连接的使用(包括仅打开)包装在使用块中。假设对连接字符串使用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
    

    并参数化用户输入的任何内容。。求你了

    希望little bobby tables不会写任何书,这些书最终会出现在这个数据库中。您是否反对用户快速增强的数据库概念?啊,这是一个功能,而不是一个缺陷。美好的我认为您需要在AddWithValues调用中的参数名称前面添加“@”,在上的MSDN页面底部有一个社区评论声称这是不必要的。我没有编译和测试上面的内容,所以,YMMV。我检查了一下,你是对的,你不需要添加“@”这个词,因为我学到了一些新东西+1.
        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