4
我學習VB.Net,但需要使用開源System.Data.SQLite ADO.Net解決方案插入事務和參數?
我在HOWTO節中的實例和SQLite數據庫的工作只在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()
謝謝你們。我找到一個使用SQLcommand.Parameters.AddWithValue()將項目添加到準備好的查詢的示例。 – Gulbahar
很高興知道,我一直在做「SqlCommand.Parameters.Add(new SqlParameter(name,value));」 - 我可以節省一些打字的時間 - 謝謝:) –