我正在连接到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;
}
}
}
答案 0 :(得分:0)
我不知道发生了什么但我只是再次运行应用程序来仔细检查是否抛出异常并获取该消息而不是它正在工作。我不知道为什么。谢谢你的帮助。