1

我遇到了一些麻烦伙计们。经过几天的劳动,调试和研究,我在倒数第三行,我卡住了。这不是完整的代码,而是相关部分。

    Dim dbProvider As String
    Dim dbSource As String
    Dim con As New OleDb.OleDbConnection
    Dim ds As New DataSet
    Dim MaxRows As Integer
    Dim sql As String
    Dim TableName As String
    TableName = TbTableName.Text
    Dim da As New OleDb.OleDbDataAdapter("SELECT * FROM  [" & TableName & "]", con)
    Dim cb As New OleDb.OleDbCommandBuilder(da)
    Dim dsNewRow As DataRow
    Dim dsNewColoumn As DataColumn

    dbProvider = "PROVIDER=Microsoft.Jet.OLEDB.4.0;"
    dbSource = "Data Source = E:\A2 Computing\Project\PasswordDatabase.mdb"

    con.ConnectionString = dbProvider & dbSource
    con.Open()

    Dim TableCreate As New OleDb.OleDbCommand("CREATE TABLE [" & TableName & "](" & "ID INTEGER NOT NULL" & ")", con)
    Dim NewColoumn As New OleDb.OleDbCommand("ALTER TABLE [" & TableName & "] ADD " & X & " VARCHAR(60)", con)

    TableCreate.ExecuteNonQuery()
    da.Fill(ds, "NewTable")

    MaxRows = ds.Tables("NewTable").Rows.Count

    ds.Tables("NewTable").PrimaryKey = New DataColumn() {ds.Tables("NewTable").Columns("CustID")}

    X = 0
    Do
        X = X + 1

        dsNewColoumn = ds.Tables("NewTable").Columns.Add
        ds.Tables("NewTable").Columns.Add(X)
        dsNewRow = ds.Tables("NewTable").NewRow()
        ds.Tables("NewTable").Rows.Add(dsNewRow)
    Loop Until X = 30


    da.InsertCommand = cb.GetInsertCommand()
    da.UpdateCommand = cb.GetUpdateCommand()
    da.Update(ds, "NewTable")
End Sub

我遇到的问题在这里

da.UpdateCommand = cb.GetUpdateCommand()

错误是

对于不返回任何键列信息的 SelectCommand,不支持为 UpdateCommand 生成动态 SQL。

我知道这意味着我的表没有主键,但我已经设置了一个。任何帮助将不胜感激!=)

4

1 回答 1

1

您需要数据库中的键列。

命令生成器不使用您在数据集中的数据列中设置的键。
事实上,如果你看代码,DA 使用的 CB create 命令,但 CB 没有引用你的 ds.Tables("NewTable").PrimaryKey,所以 CB 永远无法考虑你的 PrimaryKey。

因此,您需要在数据库中设置一个主键。

无论如何,为什么你有一个没有主键的数据库表?

更新(阅读前 9 条评论后)

  1. 您在 TableCreate SQL 命令中定义表列,当您执行此命令时,它将在数据库文件中创建表和列。
  2. 一个表可以是空的(没有行),但必须至少有一列。
  3. 您不能使用数据集/数据表抽象/对象将真实列添加到数据库中的真实表中,它确实以这种方式工作(见第 1 点)
  4. It give you the error "SSSS.ID' cannot contain a Null" because in the SQL CREATE command you are creating a table with a column called ID that is NOT NULL (see the "ID INTEGER NOT NULL" part of the command) so if you add a row to this table, the column ID MUST contain a value that is not null.
  5. your loop is adding a column at the datatable for each iteration, it doesn't work this way, you cant do that. And if you do, you are doing it wrong.
  6. The column "CustID" you are adding at the datatable exist only in the datatable (the "in-memory" abstraction of the real table) it will never exist in the DB (unless you add it to the CREATE TABLE command)

In my opinion you need to:

  1. Study a good book on RDBMS and SQL (to learn the basics of how a DB works, tables, relations, key, columns, datatype, SQL, null value....)
  2. Read some good article/book on how dataset/datatable/connection interact with a real DB
于 2012-05-08T12:48:32.233 回答