【问题标题】:insert multiple rows at a time in an SQLite database: Error with id_column在 SQLite 数据库中一次插入多行:id_column 错误
【发布时间】:2013-05-07 15:09:59
【问题描述】:

我正在尝试根据这个答案弄清楚如何在 sqlite3 数据库中进行多次插入

Is it possible to insert multiple rows at a time in an SQLite database?

它似乎工作得很好,但我有一个问题:我的表有 9 列 + 通常的 ID 是“主键自动增量不为空”......总共 10 列。

如果我使用上面主题中指出的语句,它只有在我指定一个 ID 时才有效。

如果我在语句中省略 ID,它会给我错误“SQLite 错误表权重有 10 列,但提供了 9 个值”

如果我只进行一次插入并省略 ID,它当然会自动给出下一个默认值。

如何省略多次插入的 ID?

我不知道这是否相关,但我正在 Windows CE 6 上的紧凑框架 3.5 上编程。

谢谢

'DATABASE WEIGHT COLUMNS NAME
Private Const DBWGTIdLotto = "IDLotto"
Private Const DBWGTProgressive = "ProgressiveNum"
Private Const DBWGTWeight = "Weight"
Private Const DBWGTTime = "theTime"
Private Const DBWGTStatusFlag = "StatusFlag"
Private Const DBWGTTot1 = "Tot1"
Private Const DBWGTTot2 = "Tot2"
Private Const DBWGTTot3 = "Tot3"
Private Const DBWGTPrice = "Price"

'CREATE THE DATABASE
Public Sub CreateDatabaseWeights()
    Try
        If Not File.Exists(Me.DatabasePesatePath) Then
            'Crea la tabella
            Dim sqlString As String = "CREATE TABLE " + DatabasePesateTableName + "(" _
                                    + "id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " _
                                    + DBWGTIdLotto + " INTEGER NOT NULL, " _
                                    + DBWGTProgressive + " INTEGER NOT NULL, " _
                                    + DBWGTWeight + " INTEGER, " _
                                    + DBWGTTime + " TIMESTAMP, " _
                                    + DBWGTStatusFlag + " INTEGER, " _
                                    + DBWGTTot1 + " BOOLEAN, " _
                                    + DBWGTTot2 + " BOOLEAN, " _
                                    + DBWGTTot3 + " BOOLEAN, " _
                                    + DBWGTPrice + " REAL" _
                                    + ");"
            Dim db As New SQLiteDatabase(Me.DatabasePesatePath)
            db.ExecuteNonQuery(sqlString)
        End If
    Catch ex As Exception
        AggiungiErrore("CLASS: RecordPeso => CreateDatabaseWeights: " + ex.Message)
    End Try
End Sub

'SUB TO INSERT MULTIPLE RECORDS
Public Sub AggiungiPeso(ByVal lotto As Integer, ByVal progressive As Integer, ByVal weight As Integer, ByVal flag As Byte, ByVal tot1 As Boolean, ByVal tot2 As Boolean, ByVal tot3 As Boolean, ByVal price As Single)
    Try


        Dim test(100) As Dictionary(Of String, String)
        For i As Integer = test.GetLowerBound(0) To test.GetUpperBound(0)
            'Crea il dizionario con i valori
            Dim data As New Dictionary(Of String, String)
            data.Add("id", i.ToString) 'IF I REMOVE THIS, IT GIVES ERROR !!!!!!!!!!!!!!
            data.Add(DBWGTIdLotto, lotto.ToString)
            data.Add(DBWGTProgressive, progressive.ToString)
            data.Add(DBWGTWeight, weight.ToString)
            data.Add(DBWGTTime, Now.ToString)
            data.Add(DBWGTStatusFlag, flag.ToString)
            data.Add(DBWGTTot1, IIf(tot1, "1", "0"))
            data.Add(DBWGTTot2, IIf(tot2, "1", "0"))
            data.Add(DBWGTTot3, IIf(tot3, "1", "0"))
            data.Add(DBWGTPrice, price.ToString)
            test(i) = Data
        Next

        'Salva il nuovo peso
        Dim db As New SQLiteDatabase(Me.DatabasePesatePath)
        db.MultipleInsert(DatabasePesateTableName, test)
    Catch ex As Exception
        AggiungiErrore("CLASS: RecordPeso => AggiungiPeso: " + ex.Message)
    End Try
End Sub

--------------- DATABASE CLASS --------------------

'Insert a row in the database
'<tableName>    Nome della tabella
'<data()>       Array di Dizionari con coppie di colonne/valori
'<return>       Boolean per successo o fallimento
Public Function MultipleInsert(ByVal tableName As String, ByVal data() As Dictionary(Of String, String)) As Boolean
    Dim vals As String = ""
    Dim columns As String = ""
    Dim returnCode As Boolean = True
    Try
        'Se abbiamo elementi
        If data.Count >= 1 And data(0).Count >= 1 Then
            Dim tmpQuery As String = String.Format("INSERT INTO {0} SELECT ", tableName)
            'Creo la query per l'aggiornamento
            For Each val As KeyValuePair(Of String, String) In data(0)
                tmpQuery += String.Format("'{0}' AS '{1}', ", val.Value.ToString, val.Key.ToString)
            Next
            'Remove last useless comma
            tmpQuery = tmpQuery.Substring(0, tmpQuery.Length - 2)
            'Aggiorno tutti i valori degli altri dizionari
            For i As Integer = data.GetLowerBound(0) + 1 To data.GetUpperBound(0)
                'Contatore inizio riga
                Dim j As Integer = 0
                'Add value of other dictionaries
                For Each Val As KeyValuePair(Of String, String) In data(i)
                    If j = 0 Then tmpQuery += " UNION SELECT"
                    tmpQuery += String.Format(" '{0}',", Val.Value.ToString)
                    j += 1
                Next
                tmpQuery = tmpQuery.Substring(0, tmpQuery.Length - 1)
                j = 0
            Next
            'Aggiorna il DB
            Me.ExecuteNonQuery(tmpQuery)
        End If
    Catch ex As Exception
        AggiungiRigaSuFile(ErroriPath, "CLASS: SQLiteDatabase => MultipleInsert: " + ex.Message, True, True)
        returnCode = False
    End Try
    Return returnCode
End Function

'Interact with database for purpose different from query
'<sqlString>    SQL string for interacting in DB
'<return>       Number of columns updated
Public Function ExecuteNonQuery(ByVal sqlString As String) As Integer
    Dim rowsUpdated As Integer = 0
    Try
        'Definisco la connessione al database
        Using cnn As New SQLiteConnection(dbConnection)
            cnn.Open()
            Dim cmd As New SQLiteCommand(cnn)
            cmd.CommandText = sqlString
            'Aggiorno i dati
            rowsUpdated = cmd.ExecuteNonQuery
        End Using
    Catch ex As Exception
        AggiungiRigaSuFile(ErroriPath, "CLASS: SQLiteDatabase => ExecuteNonQuery: " + ex.Message, True, True)
    End Try
    'Ritorna le righe elaborate
    Return rowsUpdated
End Function

【问题讨论】:

  • 听起来很像您实际上没有在 PK 字段上设置 AUTOINCREMENT。
  • 这里是代码,我贴了相关的subs...希望在这个过程中没有出错。 @ctacke:如果我没有自动增量...如何在不指定 ID 的情况下进行单次插入?

标签: .net database sqlite compact-framework


【解决方案1】:

不要在第一组括号中包含 id 列名。 那么也不要在值部分中包含它的任何值。

【讨论】:

  • 如果我不包含 ID,它会给我错误“SQLite 错误表权重有 10 列但提供了 9 个值”
  • 那么您在第一个列表中确定了 10 列...您不应该这样做。
  • 为什么我只申报9?我想要通常的 ID,如果我省略它,我将不会在表中找到。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-12-09
  • 1970-01-01
  • 2015-06-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多