无效的SQL语句;预期' DELETE',' INSERT'' PROCEDURE' SELECT' SELECT'或者'更新'

时间:2014-03-27 09:41:03

标签: sql vb.net

您好我的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

有什么问题?数据库的路径和数据库的表名是正确的。请帮忙!

1 个答案:

答案 0 :(得分:0)

尝试替换

sqlString = "INSERT INTO tblStuInfo (stuName, stuAddress) VALUES ('"
    & strName & "' , '" & strAddress & "')"

sqlString = "INSERT INTO tblStuInfo (stuName, stuAddress) VALUES ('"
    & strName.Replace("'", "''") & "' , '" & strAddress.Replace("'", "''") & "')"

这应解决任何SQL注入问题,当您的字符串包含' 字符时会发生这种问题。

无论如何,我认为你应该在基础表中添加(或使用)一个键,否则你将如何获得这些值?