【问题标题】:INSERT with transaction and parameters?插入事务和参数?
【发布时间】:2011-01-24 02:26:47
【问题描述】:

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

我在 HOWTO 部分找到的示例仅在 C# 中。有人可以在 VB.Net 中提供一个简单的示例,我可以学习以了解在插入多个参数时如何使用事务吗?

FWIW,这是我正在处理的代码:

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()

【问题讨论】:

    标签: vb.net parameters insert transactions system.data.sqlite


    【解决方案1】:

    事务方式应该是一样的(前提是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 驱动程序也应该如此。

    对不起,如果这段代码不是干净的 VB,我已经有大约 5 年没有碰过它了!

    【讨论】:

    • 谢谢大家。我找到了一个使用 SQLcommand.Parameters.AddWithValue() 将项目添加到准备好的查询的示例。
    • 啊,很高兴知道,我一直在做“SqlCommand.Parameters.Add(new SqlParameter(name, value));” - 我可以节省一些打字时间 - 谢谢 :)
    猜你喜欢
    • 2015-05-07
    • 2021-12-11
    • 2013-04-09
    • 1970-01-01
    • 1970-01-01
    • 2021-11-19
    • 1970-01-01
    • 2016-03-29
    • 2014-08-26
    相关资源
    最近更新 更多