我在2张桌子上搜索,每张桌子上有一个字段
Using conn As New SQLiteConnection(SQLiteConnStr)
Try
conn.Open()
Dim sql = "SELECT * FROM NamesTable"
Dim cmd As SQLiteCommand = New SQLiteCommand(sql, conn)
Dim reader As SQLiteDataReader = cmd.ExecuteReader()
Try
While (reader.Read())
ComboBox.Items.Add(reader("Name"))
End While
Catch ex As Exception
MsgBox(ex.ToString())
End Try
Dim sql = "SELECT * FROM CityTable"
Dim reader2 As SQLiteDataReader = cmd.ExecuteReader()
Try
While (reader2.Read())
ComboBox.Items.Add(reader2("City"))
End While
Catch ex As Exception
MsgBox(ex.ToString())
End Try
Catch ex As Exception
MsgBox(ex.ToString())
End Try
End Using
是因为我在2个不同的表上搜索我需要创建另一个SQLiteDataReader并且只能重用第一个?
答案 0 :(得分:2)
您没有创建新命令,因此cmd
变量仍然引用原始命令。
您需要一个新的cmd = New SQLiteCommand(sql, conn)
行,以便获得全新的命令。
你并没有重复使用读者或命令 - 这是一个新命令和一个新读者,恰好具有与原始命令相同的变量名称,但它们是全新的对象。
答案 1 :(得分:1)
考虑查询是什么:从特定表中读取某些数据的指令。用于执行此操作的DbCommand
和DbDataReader
特定于该任务 - 关于它们的重复性很小。
您实际上无法创建DbDataReader
- 它是由DbCommand
对象为您创建的(没有公共构造函数)。它对于正在运行的查询非常具体,无法使用新的SQL命令重新启动它。
这就是说你可以不重复自己来缩短你的代码:
Private Function BuildDataTableForMe(sql As String) As DataTable
Using conn As New SQLiteConnection(SQLiteConnStr)
Using cmd As New SQLiteCommand(sql, conn)
conn.Open()
Dim dt As New DataTable()
dt.Load(cmd.ExecuteReader())
Return dt
End Using
End Using
End Function
用法:
' dont use SELECT * if you dont need everything
cboCity.DataSource = BuildDataTableForMe("SELECT Id, City FROM CityTable")
' ??
cboCity.DisplayMember = "City"
cboCity.ValueMember = "Id"
cboName.DataSource = BuildDataTableForMe("SELECT Id, Name FROM NamesTable")
'??
cboName.DisplayMember = "Name"
cboName.ValueMember = "Id"