vb.net 无效的 SQL 语句;预期的“删除”、“插入”、“过程”、“选择”或“更新”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22683566/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Invalid SQL statement; expected 'DELETE', 'INSERT', 'PROCEDURE', 'SELECT', or 'UPDATE'
提问by user3414064
Hi I have an invalid sql statement error. This is my code:
嗨,我有一个无效的 sql 语句错误。这是我的代码:
Imports System.Data.OleDb 'For?OleDbConnection?
Imports System.Data 'For?ConnectionState?
Public Class WebForm1
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
Protected Sub btnInsert_Click(sender As Object, e As EventArgs) Handles btnInsert.Click
'1 declare the variables
Dim strName As String = txtName.Text
Dim strAddress As String = txtAddress.Text
'2. creates?a?new?connection?to?your?DB.
Dim conn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source='C:\Users\GT\Documents\Database11.accdb'")
If conn.State = ConnectionState.Open Then
conn.Close()
End If
'3. open?the?connection?to?your?DB.?
conn.Open()
'4. assign?your?SQL?statement?into?sqlString?variable.?
Dim sqlString As String
sqlString = "INSERT?INTO?tblStuInfo?(stuName,?stuAddress)?VALUES?('" & strName & "' , '" & strAddress & "')"
'5. create?a?new?command?that?links?your?SQL?statement?with?your?connection.?
Dim sqlcommand As New OleDbCommand(sqlString, conn)
'6. execute?your?command.
sqlcommand.ExecuteNonQuery()
End Sub
End Class
What is the problem? The path of the database and the table name of the DB is correct. Please help!
问题是什么?数据库的路径和DB的表名是正确的。请帮忙!
回答by Max
try to replace
尝试更换
sqlString = "INSERT INTO tblStuInfo (stuName, stuAddress) VALUES ('"
& strName & "' , '" & strAddress & "')"
with
和
sqlString = "INSERT INTO tblStuInfo (stuName, stuAddress) VALUES ('"
& strName.Replace("'", "''") & "' , '" & strAddress.Replace("'", "''") & "')"
this should solve any SQL injection issue, that happen when your string contain the 'character.
这应该可以解决任何 SQL 注入问题,当您的字符串包含'字符时会发生这种情况。
Anyway, I think you should add (or use) a key in the underlying table, otherwise how are you going to get these values back?
无论如何,我认为您应该在基础表中添加(或使用)一个键,否则您将如何取回这些值?

