【问题标题】:insert a database value to a string array - not working将数据库值插入字符串数组 - 不起作用
【发布时间】:2012-01-01 16:54:33
【问题描述】:

干杯,

我正在尝试将数据库值插入到我的字符串数组中。

出于某种原因,它说:

“对象引用未设置为对象的实例。”

这是我的代码:

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);

感谢帮助!

【问题讨论】:

  • 你应该绝对正确地处理连接和命令对象(如果你打算使用一个,读者也可以)。在小规模测试中,这似乎可行,但您将很快耗尽服务器上的资源(连接)。

标签: asp.net sql-server database


【解决方案1】:

rnd 为空,加一行

rnd = new Random();

在活动开始时

【讨论】:

    【解决方案2】:
    rnd = new Random();
    

    如上实例化rnd。您正在使用 null 对象,该对象会导致抛出问题中的异常。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-09
      • 2019-07-18
      • 1970-01-01
      • 2012-04-09
      • 2021-08-04
      • 2016-07-02
      • 1970-01-01
      • 2017-10-07
      相关资源
      最近更新 更多