我试图插入数据库值到我的字符串数组。
出于某种原因,它说:
“对象引用不设置到对象的实例。”
这是我的代码:
if (IsPostBack)
{
if (RadioWords.Checked == true)
{
con = new SqlConnection("Data Source=MICROSOF-58B8A5\\SQL_SERVER_R2;Initial Catalog=Daniel;Integrated Security=True");
con.Open();
string SqlCount = "SELECT COUNT(*) FROM WordGame";
SqlCommand command = new SqlCommand(SqlCount, con);
//Sets an array of the size of the database.
int count = (Int32)command.ExecuteScalar();
arrOfWords = new string[count];
//Initialize the words in the array.
for (int i = 0; i < arrOfWords.Length; i++)
{
int GetRandomNumber = rnd.Next(1, arrOfWords.Length);
string Sqlinsert = "SELECT Word FROM WordGame WHERE ID='"+GetRandomNumber+"'";
SqlCommand commandToRandom = new SqlCommand(Sqlinsert, con);
arrOfWords[i] = commandToRandom.ExecuteScalar().ToString();
}
}
其指的这条线:
int GetRandomNumber = rnd.Next(1, arrOfWords.Length);
谢谢你的助手!
你应该绝对正确地处理连接和命令对象(如果你打算使用它,阅读器也是如此)。在小规模测试中,这似乎可行,但您将很快在服务器上耗尽资源(连接)。 – Lucero 2012-01-01 17:06:24