我有两个类,一个用于数据库连接,另一个用于获取数据。当我使用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