Random Database Entry retrieval

kAnne

Active member
Joined
Jan 17, 2006
Messages
26
Programming Experience
1-3
Hi,

I was wondering how I can randomly pull an entry from an access database in vb.net?

To make more sense, I wanna pull radom questions from DB for a quiz.

Thanks,

KAnne
 
This may give you some ideas :

Public Function getQuestion() As String
Dim rowCount As Integer
Dim randomNumber As Integer
Dim filePath As String = "the path to your database"
Dim tableName As String = "the name of a table in your database"
Dim fieldName As String = "the field name in the table that holds the data you want"
Dim conString As String = "the connection string to your databse"
Dim strSQL As String = "Select * from " & tableName
Dim con As New OleDb.OleDbConnection(conString)
Dim ds As New DataSet
Dim da As New OleDbDataAdapter(strSQL, con)
con.Open()
da.Fill(ds)
con.Close()
rowCount = ds.Tables(0).Rows.Count
randomNumber = New Random().Next(0, rowCount)
Return ds.Tables(0).Rows(randomNumber).Item(fieldName)
End Function

Hope it helps. :)
 
u have to retrieve a data from database.

page_load
dim objcon as new oledbconnection("provider=microsoft.jet.oledb.4.0;datasource=d:\retrieve.mdb")
dim objcommand as new oledbcommand
objcommand.connection=objcon
objcommand.commandtext="select* from retrieve_name"

dim objclr as new class1
dim objreader as new oledbdatareader
objreader=objclr.retrieve(objcon,objcommand)
datagrid1.datasourse=objreader
datagrid1.databind()


public class class1
public function rettieve(byval onjcon as oledbconnection,byval objcommand as oledbcommand) as oledbdatareader
dim objdatareader as oledbdatareader
objcon.open()
objdatareader.objcommand.executereader(commandbehaviour.closeconnection)
return(objdatareader)
end function
end class
 
to generate random values you can use either RAND or NEWID function. Actually, i am not sure whether these functions works for access DB but you can try ... ain't that right?
If it works here is an example how to use the built-in function NEWID in conjunction with TOP and ORDER BY to return a random result set.
VB.NET:
SELECT TOP 5 fName, lName FROM EMP emp ORDER BY NEWID()


HTH
Regards ;)
 
Back
Top