Visual Basic在数据库访问中创建用户

时间:2017-02-15 15:13:41

标签: database visual-studio access-vba

我正在做一个程序而且我需要在访问时在数据库中创建用户。但是在输入数据并单击“创建用户”按钮后,它会给我一个错误。如果您将用户添加到数据库它可以工作,但如果您尝试通过程序添加它,结果是语法错误

Else
    Try
        Dim myconnection As OleDbConnection
        Dim constring As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=E:\Software_Simples\Software\DataBase.accdb"
        myconnection = New OleDbConnection(constring)
        myconnection.Open()
        Dim sqlQry As String

        'sqlQry = "INSERT INTO Usernames(Username, Password) VALUES(" & TextBox2.Text & "," & TextBox3.Text & ")"
        sqlQry = "INSERT INTO Usernames(ID_User, Username, Password) VALUES(Null,TextBox2.Text,TextBox3.Text )"

        Dim cmd As New OleDbCommand(sqlQry, myconnection)
        cmd.ExecuteNonQuery()

        myconnection.Close()
    Catch ex As Exception
        MessageBox.Show(ex.Message)
    End Try
    'Fechar
    Me.Close()
    MessageBox.Show("Utilizador criado com suecesso: " & username_create, "Aviso", MessageBoxButtons.OK)
End If

2 个答案:

答案 0 :(得分:1)

您的代码中至少存在三个问题:
1)密码是保留关键字。需要在方括号之间 2)传递给数据库时的字符串值需要在单引号之间,但是..见第3点 3)使用参数而不是字符串连接(如果密码包含单引号怎么办?)
4)像连接和命令一样处理一次性物体。

重写它

Dim constring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=E:\Software_Simples\Software\DataBase.accdb"
Dim sqlQry = "INSERT INTO Usernames(Username, [Password]) VALUES(@name, @pwd)"
Try
    Using myconnection = New OleDbConnection(constring)
    Using cmd As New OleDbCommand(sqlQry, myconnection)
        myconnection.Open()
        cmd.Parameters.Add("@name", OleDbType.VarWChar).Value = TextBox2.Text
        cmd.Parameters.Add("@pwd", OleDbType.VarWChar).Value = TextBox3.Text
        cmd.ExecuteNonQuery()
    End Using
    End Using
Catch ex As Exception
    MessageBox.Show(ex.Message)
End Try

答案 1 :(得分:0)

应该是:

sqlQry = "INSERT INTO Usernames (ID_User, Username, [Password]) VALUES (Null,'" + TextBox2.Text + "','" + TextBox3.Text + "')"