使用事务和参数的INSERT操作?

4

我正在学习VB.Net,并需要使用开源的System.Data.SQLite ADO.Net解决方案来处理SQLite数据库

我在HOWTO部分找到的示例只有C#。是否有人能提供一个简单的VB.Net示例,以便我能够学习如何在插入多个参数时使用事务?

顺便说一下,这是我正在努力的代码:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim SQLconnect As New SQLite.SQLiteConnection()
    Dim SQLcommand As SQLite.SQLiteCommand
    Dim SQLtransaction As SQLite.SQLiteTransaction

    SQLconnect.ConnectionString = "Data Source=test.sqlite;"
    SQLconnect.Open()

    SQLcommand = SQLconnect.CreateCommand

    SQLcommand.CommandText = "CREATE TABLE IF NOT EXISTS files (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, hash TEXT);"
    SQLcommand.ExecuteNonQuery()

        '================ INSERT starts here
    SQLtransaction = SQLconnect.BeginTransaction()
    Dim myparam As New SQLite.SQLiteParameter()

    SQLcommand.CommandText = "INSERT INTO [files] ([name],[hash]) VALUES(?,?)"

    SQLcommand.Parameters.Add(myparam)

    'How to set all parameters? myparam.Value

    SQLcommand.ExecuteNonQuery()
    SQLtransaction.Commit()
        '================ INSERT ends here

    SQLcommand.CommandText = "SELECT id,name,hash FROM files"
    'How to tell if at least one row?
    Dim SQLreader As SQLite.SQLiteDataReader = SQLcommand.ExecuteReader()
    While SQLreader.Read()
        ListBox1.Items.Add(SQLreader(1))
    End While

    SQLcommand.Dispose()
    SQLconnect.Close()
End Sub

谢谢。


编辑:对于那些感兴趣的人,这里有一些可行的代码:

SQLtransaction = SQLconnect.BeginTransaction()
SQLcommand.CommandText = "INSERT INTO files (name,hash) VALUES(@name,@hash)"
SQLcommand.Parameters.AddWithValue("@name", "myfile")
SQLcommand.Parameters.AddWithValue("@hash", "123456789")
SQLcommand.ExecuteNonQuery()
SQLtransaction.Commit()
1个回答

0

事务处理方式应该相同(前提是SQLite API支持事务处理)。至于多个参数,则需要为每个参数声明一个SqlParameter类的实例,然后将它们添加到查询中。

Dim myparam As New SQLite.SQLiteParameter()
myparam.Value = "Parameter 1's value"

Dim myparam2 As New SQLite.SQLiteParameter()
myparam2.Value = "Parameter 2's value"

SQLcommand.Parameters.Add(myparam)
SQLcommand.Parameters.Add(myparam2)

关于您的问题“如何判断是否至少有一行”,标准的.NET SQLReader具有“HasRows”属性。即:
If SQLreader.HasRows Then
    While SQLreader.Read()
        ListBox1.Items.Add(SQLreader(1))
    End While
End If

我认为SQLlite驱动程序也应该可以。

如果这段代码不够简洁,请见谅,我已经有五年没有碰它了!


谢谢大家。我找到了一个示例,使用SQLcommand.Parameters.AddWithValue()将项目添加到准备好的查询中。 - Gulbahar
好的,我知道了。我一直都是用“SqlCommand.Parameters.Add(new SqlParameter(name, value));”的方式。现在我可以少打一点字了,谢谢 :) - Andy Shellam

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接