2011-06-08 30 views
0

我是新来的VB编程和几天试图解决这个需要一些帮助后所遇到的问题:(!VS2010个MySqlException了未处理

我试图从VB的形式来传递一些信息我的MySQL数据库,我已经命名所有的文本框与数据库中的字段相同,并检查了所有我的数据库字段和文本框名称都是正确的

当我尝试输入信息到表单中时,我有时会得到一个错误在代码的.executeNonQuery部分。

为了测试,我输出了SQLStatement字符串到文本框(正确地从文本框中拉出所有字段),然后手动将完成的SQL查询输入到数据库中,并且它工作正常。但是,当我一次尝试这样做时,如果文本太多(如果我在每个字段中输入“a”,它似乎会失败)。它们是否限制了可以从VB传递的SQL查询的大小?所有的MySql数据库字段都设置为没有大小限制的文本。

在此先感谢!

Public Sub SaveQuote(ByRef SQLStatement As String) 
    Dim cmd As MySqlCommand = New MySqlCommand 

    With cmd 
     .CommandText = SQLStatement 
     .CommandType = CommandType.Text 
     .Connection = SQLConnection 
     .ExecuteNonQuery() 
    End With 
    SQLConnection.Close() 
    MsgBox("successfully Added!") 
    SQLConnection.Dispose() 
End Sub 

Private Sub CmdSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CmdSave.Click 

    Dim SQLstatement As String = "INSERT INTO laptopstock(forename,surname,emailaddress,contactnumber,quotedate,manufacturer,model,os,battery,drive,defects) VALUES('" & forename.Text & "','" & surname.Text & "','" & emailaddress.Text & "','" & contactnumber.Text & "', CURDATE(),'" & manufacturer.Text & "','" & modelnumber.Text & "','" & os.Text & "','" & batterycondition.Text & "','" & drivetype.Text & "','" & defects.Text & "')" 
    SaveQuote(SQLstatement) 
End Sub 

“测试SQL查询

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click 


    Dim testSQLstatement As String = "INSERT INTO laptopstock(forename,surname,emailaddress,contactnumber,quotedate,manufacturer,model,os,battery,drive,defects) VALUES('" & forename.Text & "','" & surname.Text & "','" & emailaddress.Text & "','" & contactnumber.Text & "', CURDATE(),'" & manufacturer.Text & "','" & modelnumber.Text & "','" & os.Text & "','" & batterycondition.Text & "','" & drivetype.Text & "','" & defects.Text & "')" 


    testbox.Text = testSQLstatement 

End Sub 

这里是testSQLstatement = testbox.text

INSERT INTO laptopstock(forename,surname,emailaddress,contactnumber,quotedate,manufacturer,model,os,battery,drive,defects) VALUES('Joe','Bloggs','[email protected]','07777777777', CURDATE(),'Sony','Vaio','Windows 7 Pro','Poor','DVD-Rom','Faulty Screen') 

输出从我可以看到它的格式是否正确,当我直接进入该在MySql服务器上创建一个查询

+0

不要使用像那样的字符串连接来构建查询。它使您容易受到SQL注入攻击。 – 2012-03-11 19:52:36

回答

0

您的应用程序SQL登录是否有inse rt在这张桌子上的权利?尝试在SQL控制台中直接执行授权声明: “授予在dbo.laptopstock上插入(在此添加应用程序登录)” 另外,我为什么要传递SQLStatement byref?你没有修改它,所以使用byval。这不应该影响代码,但这是一个很好的做法。

我看到你说,有时你会得到一个错误,所以我们可以推测它是工作代码。这让我相信它是在你的输入数据中。田野是否接受空值?他们是正确的格式?此外,其中一件事情不像其他日子那样。您正在传入插入中的curdate()函数。如果这些字段都像您提到的那样是字符串,那么您正在执行从日期到字符串的隐式转换。您可以使用Vb.Net等价物轻松构建插入字符串。 (Date.Now.ToString)。

最后,如果没有关于 错误的更多详细信息,则很难进行调试。由于您尚未为您的SQLConnection和MySLCommand对象发布代码(当然,您不是指MySQLCommand作为新的SQLCommand),我必须假定它们工作。

相关问题