运行两个实例时自动递增不正确

IT *_*her 5 .net vb.net sqlite system.data.sqlite

我有下面的代码运行的2个实例,它们连接到System.Data.SQLite数据库。当我使用任一实例将行插入数据库时​​,从其他实例读取时,自动递增的值(ID)不合适。这背后的原因是什么?

Imports System.Data.SQLite
Public Class Form1
    Public cnn As SQLiteConnection
    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        cnn = New SQLiteConnection("Data Source=\\abc\xx\x_backup.db;Password=password;Connect Timeout=55;FailIfMissing=True")
        cnn.ParseViaFramework = True
        cnn.Open()
    End Sub
    Public Function inserttoTable(ByVal sql As String) As DataTable

         Try
            sql = "SELECT max(ID) FROM joblog;"
            Dim mycommand As SQLiteCommand = New SQLiteCommand(cnn)
            mycommand.CommandText = sql
            MsgBox(mycommand.ExecuteScalar)
            sql = "INSERT INTO joblog (jobid) VALUES (123);"

            mycommand = New SQLiteCommand(cnn)
            mycommand.CommandText = sql
            MsgBox(mycommand.ExecuteNonQuery())
        Catch ex As Exception
            MsgBox(ex.ToString)
        End Try
Run Code Online (Sandbox Code Playgroud)

Çöđ*_*xěŕ 0

When i insert a row into the database using any one instance ,the auto incremented value(ID) is not proper when read from other instance

I suspect it's because your connections and commands aren't closed/disposed so they are left open.

对于连接的最佳建议是使用它,然后关闭/处置它。命令也是如此,确保它们已被处理。

这是执行此操作的一种方法:

 Dim intReturn As Integer
 sql = "SELECT max(ID) FROM joblog;"

 ' First query to get your scalar return value
 Using cnn As New New SQLiteConnection("Data Source=\\abc\xx\x_backup.db;Password=password;Connect Timeout=55;FailIfMissing=True")
    Using mycommand As New SQLiteCommand(sql, cnn)
       cnn.ParseViaFramework = True
       cnn.Open()

       intReturn = mycommand.ExecuteScalar
       MessageBox.Show(intReturn)

    End Using
 End Using

 ' Second query to actually do the insert
 sql = "INSERT INTO joblog (jobid) VALUES (123);"
 Using cnn As New New SQLiteConnection("Data Source=\\abc\xx\x_backup.db;Password=password;Connect Timeout=55;FailIfMissing=True")
    Using mycommand As New SQLiteCommand(sql, cnn)
       cnn.ParseViaFramework = True
       cnn.Open()

       intReturn = mycommand.ExecuteNonQuery()
       MessageBox.Show("Records affected " & intReturn)

    End Using
 End Using
Run Code Online (Sandbox Code Playgroud)

另一方面,请考虑使用SQL 参数,否则您可能容易受到 SQL 注入攻击。