目前,我希望从Access数据库中列的前5行填充5个TextBoxes。
我尝试过几个不同的SQL查询,但没有成功。
下面是第一个框的工作代码:
Try
Dim con As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Test\Response.mdb;")
Dim cmd As New OleDbCommand
con.Open()
cmd.Connection = con
cmd.CommandText = "SELECT * FROM question"
cmd.Prepare()
Dim Trace = cmd.ExecuteReader
With Trace
.Read()
q1txt.Text = .Item("questiontext")
.Close()
End With
Catch
End Try该代码工作非常好,但是当我试图扩展到包含下一个4的时候,我无法让它工作,也无法找到任何可以帮助我的信息。
我尝试编写一个不同的查询来填充每个框
select * from question limit n-1, 1和
select top 1 field from question在几十个其他的所有抛出的异常或另一个。
有没有人知道如何修改我的代码以便我能够有效地告诉它:
SELECT TOP 5 FROM question
q1txt.Text = .item("ROW1")
q2txt.Text = .item("ROW2")
q3txt.Text = .item("ROW3")
q4txt.Text = .item("ROW4")
q5txt.Text = .item("ROW5")谢谢史蒂夫帮我解决这个问题!我现在使用的代码如下:
Dim boxes = {q1txt, q2txt, q3txt, q4txt, q5txt}
Dim index As Integer = 0
Using con = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Test\Response.mdb;")
Using cmd = New OleDbCommand("SELECT TOP 5 * FROM question", con)
con.Open()
Using Trace = cmd.ExecuteReader
For Each item In boxes
With Trace
.Read()
boxes(index).Text = .Item("questiontext")
index += 1
End With
Next
End Using
End Using
End Using发布于 2014-03-24 10:21:11
Access没有像MySql那样的限制关键字。您可以在某一列上按顺序排序,然后取前5列。我不知道您是否有任何可以排序的列,所以我显示没有ordered子句的代码,而是按数据库给它们的顺序获取前5条记录。
Dim boxes = new TextBox() {q1Text, q2Text, q3Text, q4Text, q5Text }
Dim index As Integer = 0
Using con = New OleDbConnection(".....")
Using cmd = New OleDbCommand("SELECT TOP 5 * FROM question", con)
con.Open()
Using Trace = cmd.ExecuteReader
While Trace.Read()
boxes(index).Text = Trace.Item("questiontext")
index += 1
End While
End Using
End Using
End Using每次读取时,您都会在不同的TextBox中放置不同的记录,因此我构建了一个文本框数组,并使用索引填充了正确的框。
还请注意,我已经在您的一次性对象周围添加了are语句,以确保它们被正确关闭和处理。
https://stackoverflow.com/questions/22606325
复制相似问题