VB.NET SQL Server插入-ExecuteNonQuery:连接属性尚未初始化
||
在表单加载事件中,我连接到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
没有找到相关结果
已邀请:
5 个回复
惭法搽
连接处理-您还需要从负载处理程序中删除“ MyConnection.Open \”。只需打开它,然后像现在一样在您的Click Handler中将其关闭即可。这不会导致错误。 参数化SQL-尽管您没有使用存储过程,但仍需要使用SQL参数。这不是您的错误的原因。正如Conrad提醒我的那样,您的原始代码将用户的值直接转储到SQL语句中。除非您使用SQL参数,否则恶意用户将窃取您的数据。
蕉衫
属性:
祁澈盘哼颗
痴浪墨
终端模块
捻盒愧杯
并请用户输入任何参数。