0

我正在尝试在 Visual Basic 2010 上将 DataTables 和 .mdb 数据库用于以下功能,但它确实有效:

我有一个现有的 .mdb 数据库,其中包含一个表“日期”和该表中的命名列。我想在数据库中添加一个包含新信息的新行。所以我使用以下代码连接到数据库:

sql = "SELECT * FROM Daten"

            Dim connection As New OleDb.OleDbConnection

            Try
                connection.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" & "Data Source=" & pfad_netzdb
            Catch e As Exception
                MessageBox.Show(e.Message)
            End Try
            Dim adapter As OleDb.OleDbDataAdapter = New OleDb.OleDbDataAdapter(sql, connection)

之后,我用数据库的给定数据填充 DataTable:

Dim daten As New DataTable

            adapter.Fill(daten)

之后,我想向 DataTable 添加一个行并用新信息填充该行:

daten.Rows.Add()
daten.Rows(daten.Rows.Count - 1)(0) = "kdjfk"
daten.Rows(daten.Rows.Count - 1)(1) = "dkjfk"
daten.Rows(daten.Rows.Count - 1)(2) = "kdjfkd"

之后,我想将更改后的 DataTable 与新行和行中的新信息一起发送回数据库。我认为这是我的代码没有达到我期望的地方。我正在尝试这样,但它确实有效:

adapter.Update(daten)

谁能帮助我为什么此代码不起作用?谢谢你的帮助!

4

2 回答 2

0

也可以使用参数化的方式插入记录

Dim adapter As OleDbDataAdapter = New OleDbDataAdapter()
Dim command As OleDbCommand

' Create the SelectCommand.
command = New OleDbCommand("SELECT * from Daten", connection)

adapter.SelectCommand = command

' Create the InsertCommand.
command = New OleDbCommand( _
    "INSERT INTO Daten(ColumnName1, ColumnName2,ColumnName3) " & _
    "VALUES (?, ?,?)", connection)

command.Parameters.Add( _
    "ColumnName1", OleDbType.VarChar, 40, "kdjfk") //Replace with correct column name and data type
command.Parameters.Add( _
    "ColumnName2", OleDbType.VarChar, 40, "dkjfk") //Replace with correct column name and data type
command.Parameters.Add( _
    "ColumnName3", OleDbType.VarChar, 40, "kdjfkd")//Replace with correct column name and data type

adapter.InsertCommand = command
Return adapter
于 2013-03-11T08:28:04.073 回答
0

你提供了InsertCommand吗?您可以使用CommandBuilder.

Dim conString = "Provider=Microsoft.Jet.OLEDB.4.0;" & "Data Source=" & pfad_netzdb
Using connection As New OleDb.OleDbConnection(conString)
    Using adapter = New OleDb.OleDbDataAdapter("SELECT * FROM Daten", connection)
        Dim builder = New OleDb.OleDbCommandBuilder(adapter)
        builder.GetInsertCommand()
        Dim daten As New DataTable
        daten.Columns.Add("ColumnName1", GetType(String)) ' provide the correct name+type '
        daten.Columns.Add("ColumnName2", GetType(String)) ' provide the correct name+type '
        daten.Columns.Add("ColumnName3", GetType(String)) ' provide the correct name+type '
        Dim newRow = daten.Rows.Add()
        newRow(0) = "kdjfk"
        newRow(1) = "dkjfk"
        newRow(2) = "kdjfkd"
        connection.Open()
        adapter.Update(daten)
    End Using
End Using
于 2013-03-11T08:05:12.653 回答