具有多个实例的system.data.sqlite连接

问题描述 投票:1回答:1

我正在运行以下代码的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
.net vb.net sqlite system.data.sqlite
1个回答
0
投票

当我使用任何一个实例向数据库中插入一行时,从其他实例读取时自动递增的值(ID)都不正确

怀疑是因为您的连接和命令未关闭/未布置因此它们保持打开状态。

关于连接的最佳建议是打开它,执行所需的操作,然后关闭/处置此连接。您的命令也一样,但是您只需要确保将它们丢弃即可。

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

 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注入攻击。

© www.soinside.com 2019 - 2024. All rights reserved.