2016-01-22 52 views
0

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

谁初始化'Data.Datatable'属性? – Dennis

+0

您是否在调用'GetCivicEntities()'之前创建**(实例化)'Datatable'?该方法本身从来没有实例化该数据表 - 所以它已经在调用该方法之前实例化..... –

+0

检查我的解决方案,并告诉我是否有帮助。 – mybirthname

回答

3

你的数据表是空的,因为你有这样的问题。这应该解决它。

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

邑,它的工作,thax –

+0

@ShalinkaRandeniya确定答案是正确的。 – mybirthname

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(); 
} 
+0

它的工作,但我仍然得到我的代码的问题。它同样的事情,它在我通过存储过程调用时起作用。 –

+0

这是如何回答这个问题的?您的代码示例与OP显着不同。此外,在使用它们之前声明所有变量有什么意义? – Dennis

相关问题