为什么数据表在通过 SQL 命令文本执行时返回 Null
本文关键字:执行 文本 返回 Null 命令 SQL 数据表 为什么 | 更新日期: 2023-09-27 18:31:28
我有两个类,一个用于数据库连接,另一个用于获取数据。当我使用 SqlCommand
类型作为存储过程时,它会正确返回数据表,但是当我将命令类型更改为文本并正确更改命令文本时,它会返回一个 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;
}
}
您的数据表为空,因此您遇到了此问题。这应该可以解决它。
cmd.CommandText = "SELECT Id, Description, StateId ,EntityTypeId FROM CivicEntities";
Datatable = new DataTable();
ada.Fill(Datatable);
return true;
类结构有问题。检查这个
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();
}