【问题标题】:Error when inserting data into a MS Access table将数据插入 MS Access 表时出错
【发布时间】:2017-04-25 16:27:55
【问题描述】:

如何将数据插入 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

【问题讨论】:

标签: vb.net ms-access


【解决方案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.ShowMsgBox 存在于 VB6 并最终委托给 MessageBox 所以使用 MessageBox.Show 是有意义的:

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

最后我会考虑实现Using,这将有助于关闭dispose你的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,这可能会给你一些关于如何最好地做到这一点的想法。

【讨论】:

    【解决方案2】:

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

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-20
      • 2019-08-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多