.net - 运行两个实例时自动增量不正确

标签 .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

最佳答案

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/

相关文章:

vb.net - 如何在 vb.net 中获取 ListView 的 SelectedItem 或 SelectedIndex?

c# - log4net 特定类应使用 appender

vb.net "if statement"包含加号

jquery - 从 formview edititemtemplate 文本框内部访问 jQuery 函数

sqlite - 将 SQLite 与 Xamarin.Forms 跨平台项目结合使用

android - ORDER BY Month, Year DESC 在 SQLite 中不起作用

ios - 数据库在使用 xamarin ios 的构建之间未保留

c# - .NET (C#) MySqlDbType 用于 char

c# - 如何将 .NET 库移动到子目录?

c# - 为什么用户控件不从 View 模型绑定(bind)?