我正在使用下面的代码从数据库中获取数据。但是当断点转到 var k 之后的任何一行时,会立即引发异常。
DataSet ds = new DataSet();
try
{
using (SqlConnection con = new SqlConnection())
{
con.ConnectionString = @"Data Source = sql\db1,5000; Initial Catalog = uatdb; Integrated Security = SSPI";
using (SqlDataAdapter da = new SqlDataAdapter())
{
var k = con.State;
更新:
从答案中添加了这一行,但没有帮助,仍然是同样的错误
da.selectcommand=new sqlcommand();
da.SelectCommand.Connection.ConnectionString= con.ConnectionString;
da.SelectCommand.CommandText = "usp_checkstatus";
da.SelectCommand.Parameters.Add("@id", SqlDbType.Int).Value = TextBox1.Text.ToString(); ;
da.SelectCommand.CommandType = CommandType.StoredProcedure;
// da.SelectCommand.Parameters.AddWithValue("@buildid", TextBox1.Text);
da.Fill(ds);
return ds;
}
}
}
****异常详情:****
object reference not set to an instance of object.Connection state is closed always and DB,connection strings are correct,i am not opening connection,since data adapter will open connection for me.
答案可能很简单,但现在已经占用了我将近 4 个小时的时间。非常感谢任何帮助。
注意: 我可以使用 sqlcommand 来处理下面问题中的代码,但我想尝试使用数据适配器
How to use a DataAdapter with stored procedure and parameter
最佳答案
您应该将创建的 SqlConnection 设置为您的 SqlDataAdapter。没有必要打开它,因为适配器会在它关闭时为您打开它,但适配器必须知道连接。
DataSet ds = new DataSet();
try
{
using (SqlConnection con = new SqlConnection(@"Data Source = sql\db1,5000;
Initial Catalog = uatdb; Integrated Security = SSPI"))
using (SqlDataAdapter da = new SqlDataAdapter("usp_checkstatus", con))
{
da.SelectCommand.CommandType = CommandType.StoredProcedure;
da.SelectCommand.Parameters.Add("@id", SqlDbType.Int).Value = Convert.ToInt32(TextBox1.Text);
da.Fill(ds);
return ds;
}
}
也无需创建特定的 SqlCommand。当您创建适配器并传递一个存储过程名称时,会自动为您创建一个新的 SqlCommand,当然您仍然需要设置它的参数和它的 CommandType。 (关于参数的注释,我不确定这是否会导致您的 sp 中出现错误结果,但如果您想传递整数然后将输入转换为整数似乎是安全的)
关于c# - 数据适配器.选择命令.连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31357337/