我有兩個類,一個用於數據庫連接,另一個用於獲取數據。當我使用SqlCommand
類型作爲存儲過程時,它會正確返回數據表,但是當我將命令類型更改爲文本並正確更改命令文本時,它將返回空值。這是爲什麼發生?爲什麼Datatables在通過SQL命令文本執行時返回Null?
1個
public class DB_Connection
{
public SqlConnection cnn;
public SqlCommand cmd;
public SqlDataAdapter ada;
public DB_Connection()
{
cnn = new SqlConnection("Data Source=svr01;Initial Catalog=PDFScramble;Integrated Security=True");
cnn.Open();
cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;// *changed in here SP or Text*
cmd.Connection = cnn;
ada = new SqlDataAdapter();
ada.SelectCommand = cmd;
}
2級
public class Data : DB_Connection
{
public string DException { get; set; }
public DataTable Datatable { get; set; }
public bool GetCivicEntities()
{
try
{
cmd.CommandText = "SELECT Id, Description, StateId ,EntityTypeId FROM CivicEntities";
ada.Fill(Datatable);// *Null in here*
return true;
}
catch (Exception ex)
{
DException = ex.Message;
return false;
}
}
誰初始化'Data.Datatable'屬性? – Dennis
您是否在調用'GetCivicEntities()'之前創建**(實例化)'Datatable'?該方法本身從來沒有實例化該數據表 - 所以它已經在調用該方法之前實例化..... –
檢查我的解決方案,並告訴我是否有幫助。 – mybirthname