2010-03-05 29 views
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() 

回答

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驱动程序也应该如此。

对不起,如果这段代码不干净VB,我大约5年没有触及它!

+0

谢谢你们。我找到一个使用SQLcommand.Parameters.AddWithValue()将项目添加到准备好的查询的示例。 – Gulbahar

+0

很高兴知道,我一直在做“SqlCommand.Parameters.Add(new SqlParameter(name,value));” - 我可以节省一些打字的时间 - 谢谢:) –