开发者

Retrieving random data from sql database no repeat

Hi im creating a program where when the form loads random data will retrieve from the database and my problem is the code for not repeating the data again. im using vb 2008 and sql database, programming language : C#

for example:

Data in Database

Word_ID | Word
1 | eye
2 | cheese
3 | mouse

Then form loads it will retrieve random data and display in the label

example output:

cheese

so cheese now will not display on the next random

my code:

SqlConnection con开发者_高级运维n =
new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\sony\Documents\Visual Studio 2008\Projects\Hangman_Final\Hangman_Final\hangman_db.mdf;Integrated Security=True;User Instance=True");

conn.Open();

SqlCommand command = conn.CreateCommand();
command.CommandText = "SELECT TOP 1 Words from word order by NEWID()";
command.CommandType = CommandType.Text;

SqlDataReader reader = command.ExecuteReader();

// display the results
while (reader.Read())
{
    string output = reader["Words"].ToString();
    label5.Text = output;
}

// close the connection
reader.Close();
conn.Close();


Store words into List<String>. Get an element at random index from the list , print it and remove it.


Is it just a matter of including the word that was just loaded as a 'and WORD <> 'PreviousWord'' in the where clause of you select statement?


Assuming that you are storing the words along with an integer index in the database table, why not generate a random number (between the max number/index of words you have) in C# (using Random) and then fetch the word matching the index.


Store the words in an collection and count it. Then use Random ? But this depends on how many words you got in the database.


Here's how I've done this. As in your example, each record in the database has a numeric ID. I get the min and max ID and build a list of random numbers for whatever number of records I want. I exclude duplicate numbers during this process. Handling this in memory with an integer list is much faster than repeated database queries. Once the list of unique random numbers is created, then the records are pulled from the database using the members of the list as the criteria.

You can add in additional checks in case your ID's aren't sequential and for other conditions.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜