SQLDataReader未返回任何数据

本文关键字:数据 任何 返回 SQLDataReader | 更新日期: 2023-09-27 17:58:35

我正在连接到SQLExpress服务器,并试图从表中返回数据。代码正在进行连接,但当我从查询中读取结果时,没有数据。我已经在SSMS中执行了查询,它运行得很好。我还在另一个应用程序中使用了相同的代码,它运行得很好。我现在很困惑。这是我的连接程序:

private void ConnectToDatabase()
    {
        string strConnection = null;

        try
        {
            if (sqlConn != null)
            {
                sqlConn.Close();
            }

            strConnection = "Data Source=CASS-LAPTOP''SQLEXPRESS; Initial Catalog=NBFoodPantry;Integrated Security=true";
            sqlConn = new SqlConnection(@strConnection);
            try
            {
                sqlConn.Open();
            }
            catch (Exception ex)
            {
                string strMsg;
                strMsg = "ConnectToDatabase: SQL Open failed with error, " + ex.Message + ".";
                System.Windows.MessageBox.Show(strMsg);
            }
        }
        catch (Exception ex)
        {
            string strMsg;
            strMsg =" ConnectToDatabase: failed with error, " + ex.Message  + ".";
            System.Windows.MessageBox.Show(strMsg);
        }
    }

以下是查询表的代码:

private void LoadCitys()
    {
        bool blnSuccess = false;
        int intItemCnt;
        string strQuery;

        if (sqlConn != null && sqlConn.State == ConnectionState.Open)
        {
            intItemCnt = 0;
            strQuery = "select distinct city from zipcodes order by city";
            try
            {
                using (SqlCommand sqlCmd = new SqlCommand(strQuery, sqlConn))
                {
                    SqlDataReader sqlDataRead = sqlCmd.ExecuteReader();
                    while (sqlDataRead.Read())
                    {
                        string strDBNme = sqlDataRead.GetString(intItemCnt);
                        cmbxACCity.Items.Add(strDBNme);
                    }
                    sqlDataRead.Close();
                    sqlCmd.Dispose();
                    cmbxACCity.SelectedItem = cmbxACCity.Items.GetItemAt(0);
                }
                blnSuccess = true;
            }
            catch (Exception exQuery)
            {
                System.Windows.MessageBox.Show("LoadCitys: Error, " + exQuery.Message + ", has occurred.");
                blnSuccess = false;
            }
        }
    }

SQLDataReader未返回任何数据

我不知道发生了什么,但我只是再次运行应用程序,仔细检查是否引发了异常,并获取该消息,但它是否正常工作。我不知道为什么。谢谢你的帮助。