.NET访问错误INSERT INTO

时间:2017-08-15 21:06:13

标签: vb.net ms-access

我正在尝试使用VISUAL STUDIO将文本框文本插入数据库这里是我的代码:

class Post extends Model
{
    public function addComment($body)
    {
        Comment::create([
            'body' => $body,
            'post_id' => $this->id
        ]);
    }

    public function comments()
    {
        return $this->hasMany(Comment::class);
    }
}

但我得到一个异常错误,包括:

  

附加信息:INSERT INTO语句中的语法错误。

我的代码出了什么问题,我的引号也围着这些值!

2 个答案:

答案 0 :(得分:0)

直接答案是密码是Access中的保留字。因此:

Dim sqlQry As String = "INSERT INTO Admins (USERNAME, [PASSWORD]) VALUES('" & usernme & "','" & passwrd & "')"

也就是说,当您使用非清理用户输入进行直接连接时,执行会遵循@Plutonix发布的建议。

答案 1 :(得分:0)

你可以这样试试。

*Imports System.Data.OleDb
Public Class Form1
    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
        ' Requires: Imports System.Data.OleDb
        ' ensures the connection is closed and disposed
        Using connection As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;" & _
            "Data Source=""C:\your_path_here\InsertInto.mdb"";" & _
            "Persist Security Info=False")
            ' open connection
            connection.Open()
            ' Create command
            Dim insertCommand As New OleDbCommand( _
                "INSERT INTO Table1([inputOne] , [inputTwo] , [inputThree]) " & _
                "VALUES (@inputOne, @inputTwo, @inputThree);", _
                connection)
            ' Add the parameters with value
            insertCommand.Parameters.AddWithValue("@inputOne", TextBox1.Text)
            insertCommand.Parameters.AddWithValue("@inputTwo", TextBox2.Text)
            insertCommand.Parameters.AddWithValue("@inputThree", TextBox3.Text)
            ' you should always use parameterized queries to avoid SQL Injection
            ' execute the command
            insertCommand.ExecuteNonQuery()
            MessageBox.Show("Insert is done!!")
        End Using
    End Sub
End Class*