将数据插入MS Access表时出错

时间:2017-04-07 02:30:22

标签: vb.net ms-access

如何将数据插入MS Access表?当我尝试时,我收到了一个错误。

代码:

If TextBox1.Text = Nothing And TextBox2.Text = Nothing Then
    MsgBox("No Username and Password inserted")
    TextBox1.Focus()

Else

    If Not con.State = ConnectionState.Open Then
        'open connection if it is not yet open
    End If

    cmd.Connection = con
    'add data to table
    cmd.CommandText = "insert into loginTable(username, password, typeofuser) values ('" & Me.TextBox1.Text & "', '" & Me.TextBox2.Text & "', '" & Me.ComboBox1.Text & "')"

    cmd.ExecuteNonQuery()

    'refresh data in list

    'close connection
    con.Close()
End If

2 个答案:

答案 0 :(得分:1)

首先,您不要打开连接:

con.Open()

接下来,passwordreserved word in MS Access。您需要将password括在方括号中:

[password]

您正在连接字符串而不是使用参数:

cmd.Parameters.Add("@username", OleDbType.VarChar).Value = txtUsername.Text
cmd.Parameters.Add("@password", OleDbType.VarChar).Value = txtPassword.Text
cmd.Parameters.Add("@typeofuser", OleDbType.VarChar).Value = cmbTypeOfUser.Text

请注意为TextBoxComboBox控件指定正确的名称,而不是使用TextBox1TextBox2ComboBox1。这有助于正确识别每个控件:

txtUsername
txtPassword
cmbTypeOfUser

不再使用MsgBox并使用MessageBox.Show。 VB6存在MsgBox,无论如何最终委托给MessageBox,因此使用MessageBox.Show是有道理的:

MessageBox.Show("No Username and Password inserted")

最后,我会考虑实施Using,这将有助于关闭配置您的SQL对象:

Using cmd As New OleDbCommand(command, connection)

End Using

所有代码看起来都像这样:

If txtUsername.Text = Nothing And txtPassword.Text = Nothing Then

    MessageBox.Show("No Username and Password inserted")
    TextBox1.Focus()

Else

    Using con As New OleDbConnection(connectionString),
          cmd As New OleDbCommand("INSERT INTO [loginTable] ([username], [password], [typeofuser]) VALUES (@username, @password, @typeofuser)", con)

        con.Open()

        cmd.Parameters.Add("@username", OleDbType.VarChar).Value = txtUsername.Text
        cmd.Parameters.Add("@password", OleDbType.VarChar).Value = txtPassword.Text
        cmd.Parameters.Add("@typeofuser", OleDbType.VarChar).Value = cmbTypeOfUser.Text

        cmd.ExecuteNonQuery()

    End Using

End If

这不在本问题的范围内,但我也会考虑加密密码。将它们存储为纯文本是不好的做法。看看SO问题; Best way to store password in database,可能会就如何做到这一点给你一些想法。

答案 1 :(得分:0)

有(至少)几种方法可以做到这一点。所以,试试吧。 。

Imports System.Data.OleDb

Public Class Form1

    Private ConnectionString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Excel\Desktop\Coding\Microsoft Access\Northwind.mdb;"
    Private NewIdentifer As Integer = 0
    Private InsertStatement As String = "INSERT INTO Employee (LName) Values(@LName)"
    Private IdentifierStatement As String = "Select @@Identity"

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


    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Using cn As New OleDbConnection(ConnectionString)
            Using cmd As New OleDbCommand("SELECT * FROM Employee", cn)
                Dim dt As New DataTable
                cn.Open()
                Dim Reader As OleDbDataReader = cmd.ExecuteReader()
                dt.Load(Reader)
                Dim dv = dt.DefaultView
                DataGridView1.DataSource = dv
            End Using
        End Using
    End Sub

    'End Sub

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

        If Not String.IsNullOrEmpty(txtLastName.Text) Then
            Using cn As New OleDbConnection(ConnectionString)
                Using cmd As New OleDbCommand(InsertStatement, cn)
                    cmd.Parameters.AddWithValue("@LName", txtLastName.Text)
                    cn.Open()
                    cmd.ExecuteNonQuery()
                    cmd.CommandText = IdentifierStatement
                    NewIdentifer = CInt(cmd.ExecuteScalar())
                    Dim Row As DataRowView = CType(DataGridView1.DataSource, DataView).AddNew
                    Row("Fname") = NewIdentifer
                    Row("LName") = txtLastName.Text
                    Row.EndEdit()
                    DataGridView1.CurrentCell = DataGridView1(0, DataGridView1.RowCount - 1)
                    txtLastName.Text = ""
                End Using
            End Using
        Else
            MsgBox("Please enter a name")
        End If

    End Sub
End Class

另外,试试。 。

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:\Users\Ryan\Desktop\Coding\DOT.NET\Samples VB\Insert Into MS Access Table from Textbox\WindowsApplication1\bin\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
相关问题