我需要從數據庫中的字段檢索值。我有使用下面的代碼。但價值checkOrderId
(我需要)顯示SQL字符串,而不是數據庫中的值。我不知道它爲什麼這樣做。請有人幫助我嗎?該查詢是否正確地從數據庫檢索數據?
string connectionString = "Data Source = xxyyzz;Initial Catalog = xyz; Integrated Security = True";
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
string tableName = "[GIS].[SecondaryTraffic].[PotentialBackHauls]";
string checkOrderId = "Select TOP 1 OrderID From" + tableName + "ORDER BY InsertDate DESC";
SqlCommand cmd = new SqlCommand(checkOrderId, connection);
//cmd.ExecuteNonQuery();
OpenPop.Pop3.Pop3Client popConn = new OpenPop.Pop3.Pop3Client();
if (orderIdentity == checkOrderId)
{
popConn.DeleteMessage(messageNumber);
}
connection.Close();
我是新來的,沒有聲望立即回答我的問題。在大家的幫助下,我得到了這個解決方案...偉大的幫助,比每個人...以下是我的代碼。
string connectionString =「Data Source = EAEDEV; Initial Catalog = GIS; Integrated Security = True」;
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string tableName = "[GIS].[SecondaryTraffic].[PotentialBackHauls]";
string checkOrderId = "Select TOP 1 OrderID From " + tableName + " ORDER BY InsertDate DESC";
SqlCommand cmd = new SqlCommand(checkOrderId, connection);
string valueReturned = (string)cmd.ExecuteScalar();
OpenPop.Pop3.Pop3Client popConn = new OpenPop.Pop3.Pop3Client();
if (orderIdentity == valueReturned)
{
popConn.DeleteMessage(messageNumber);
}
connection.Close();
}
您需要執行該命令並檢索結果。請參閱[文檔SqlCommand.ExecuteScalar](http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar.aspx)的完整示例 –
或者可以使用DataReader而不是ExecuteNonQueey 。 –
除了別人在說什麼之外,你真的應該把連接包裝在一個使用塊中。 –