[英]How to get result from stored procedure and save result in a class attributes
I have following code: 我有以下代码:
public static void executeStoredProcedure(SqlCommand sp)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString=Connection.getConnection();
conn.Open();
sp.CommandType = CommandType.StoredProcedure;
sp.Connection = conn;
sp.ExecuteNonQuery();
conn.Close();
}
This code executes the stored procedure. 此代码执行存储过程。
But my stored procedure is 但我的存储过程是
Create procedure [dbo].[selectAllItems]
(@ItemCode varchar(50) )
as
begin
select * from Item where ItemCode = @ItemCode
end
It will return rows but how to get this result in above c# code 它将返回行,但如何在上面的c#代码中获得此结果
You need to use a SqlDataReader
to read the result set returned by the stored procedure: 您需要使用SqlDataReader
来读取存储过程返回的结果集:
using (SqlConnection conn = new SqlConnection(Connection.getConnection()))
using (SqlCommand sp = new SqlCommand("dbo.selectAllItems", conn))
{
sp.CommandType = CommandType.StoredProcedure;
sp.Parameters.Add("@ItemCode", SqlDbType.Int).Value = your-item-code-value-here;
conn.Open();
using (SqlDataReader rdr = sp.ExecuteReader())
{
while (rdr.Read())
{
// read the values from the data reader, e.g.
// adapt to match your actual query! You didn't mentioned *what columns*
// are being returned, and what data type they are
string colValue1 = rdr.GetString(0);
int colValue2 = rdr.GetInt(1);
}
}
conn.Close();
}
With those values read from the SqlDataReader
, you could eg create an object type and set its properties - or something like that - totally depends on what you want to do. 使用从SqlDataReader
读取的值,您可以创建一个对象类型并设置其属性 - 或类似的东西 - 完全取决于您想要做什么。
And of course : using an ORM like Entity Framework would save you from having to write a lot of this type of code - EF would handle this for you - automagically . 当然:使用类似实体框架的ORM将节省您不必写了很多这种类型的代码- EF会处理这个给你-自动的。
you need to parse the parameter to you stored procedure like below 您需要将参数解析为您的存储过程,如下所示
sp.Parameters.AddWithValue("@ItemCode", itemcode);
sample code 示例代码
public DataTable SelectAllItems(string itemCode)
{
DataTable dt = new DataTable();
using (SqlConnection conn = new SqlConnection(Connection.getConnection()))
using (SqlCommand cmd = new SqlCommand("selectAllItems", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@ItemCode", itemCode);
conn.Open();
using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))
{
adapter.Fill(dt);
}
}
return dt;
}
You can use SQL Data reader Check the following example. 您可以使用SQL数据阅读器检查以下示例。
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.read.aspx http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.read.aspx
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.