我正在运行以下代码的 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
最佳答案
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
我怀疑这是因为您的连接和命令未关闭/处置,因此它们保持打开状态。
连接的最佳建议是使用它,然后关闭/处置它。命令也是如此,确保它们已被处理。
这是执行此操作的一种方法:
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
另一方面,请考虑使用 SQL Parameters ,否则可能容易受到SQL注入(inject)攻击。
关于.net - 运行两个实例时自动增量不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58116937/