加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

VB.NET SQL Server插入 – ExecuteNonQuery:尚未初始化Connecti

发布时间:2020-12-17 07:26:23 所属栏目:百科 来源:网络整理
导读:在表单加载事件中,我连接到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") myCon
在表单加载事件中,我连接到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

解决方法

>连接分配 – 您没有设置SQLCommand的连接属性.您可以在不添加代码行的情况下执行此操作.这是导致错误的原因.

myCommand = New SqlCommand("INSERT INTO tblBook(BookCode," & txtAmount.Text & ")",MyConnection)

>连接处理 – 您还需要从加载处理程序中删除“MyConnection.Open”.只需打开它并在您的Click Handler中关闭它,就像您目前正在做的那样.这不会导致错误.
>参数化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)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读