我在执行代码时遇到错误,CommandText属性尚未初始化
public DataTable Mappingdataload(string name)
{
try
{
string spname = "";
switch (name.ToLower())
{
case "student":
spname = "RetrieveStudent";
break;
case "organization":
spname = "RetrieveOrganization";
break;
}
SqlCommand cmd = new SqlCommand();
cmd.Connection = SQLConClass.GetSQLConnection();
cmd.CommandText = spname;
cmd.CommandType = System.Data.CommandType.StoredProcedure;
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(cmd);
DataTable dataTable = new DataTable();
sqlDataAdapter.Fill(dataTable);
return dataTable;
}
catch (Exception)
{
throw;
}
}
答案 0 :(得分:0)
由于未初始化命令文本而收到此错误:)
总是最好先建立连接,然后再创建命令。检查下面的代码。
var conn = SQLConClass.GetSQLConnection();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = spname;
cmd.CommandType = CommandType.StoredProcedure;
最好像这样使用它:
using (var conn = SQLConClass.GetSQLConnection())
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = spname;
cmd.CommandType = CommandType.StoredProcedure;
using (var reader = cmd.ExecuteReader())
{
....
}
}