为什么Datatables在通过SQL Command文本执行时返回Null?

时间:2016-01-22 06:01:38

标签: c# sql-server

我有两个类,一个用于数据库连接,另一个用于获取数据。当我使用SqlCommand类型作为存储过程时,它会正确返回数据表,但是当我将命令类型更改为文本并正确更改命令文本时,它将返回空值。为什么会这样?

第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;
        }
    } 

2 个答案:

答案 0 :(得分:3)

您的数据表为空,因为您遇到此问题。这应该解决它。

 cmd.CommandText = "SELECT Id, Description, StateId ,EntityTypeId FROM CivicEntities";
 Datatable = new DataTable();
 ada.Fill(Datatable);
 return true;

答案 1 :(得分:0)

类结构有问题。请查看

using (SqlConnection conn = new SqlConnection("connectionString"))
{
SqlCommand cmd = null;
SqlParameter prm = null;
SqlDataAdapter dad = null;
DataTable dt = new DataTable();

cmd = new SqlCommand("SPName", conn);
cmd.CommandType = CommandType.StoredProcedure;

conn.Open();
dad = new SqlDataAdapter(cmd);


dad.Fill(dt);
conn.Close();
}


using (SqlConnection conn = new SqlConnection("connectionString"))
{
SqlCommand cmd = null;
SqlParameter prm = null;
SqlDataAdapter dad = null;
DataTable dt = new DataTable();

cmd = new SqlCommand("select * from dummy",conn);
cmd.CommandType = CommandType.StoredProcedure;
conn.Open();
dad = new SqlDataAdapter(cmd);


dad.Fill(dt);
conn.Close();
}