C#调用梦数据库存储过程方法

如题所述

//连接字符串
private string strConn = ConfigurationManager.ConnectionStrings["connstr"].ConnectionString;
//连接对象
private SqlConnection conn;

private void Form1_Load(object sender, EventArgs e)
{
//实例化连接对象
conn = new SqlConnection(strConn);
}

private void button1_Click(object sender, EventArgs e)
{
//判断是否数据库连接成功
if (conn.State == System.Data.ConnectionState.Closed)
{
//连接数据库
conn.Open();
}
//创建SQL命令对象,GetMaxPrice参数为存储过程名
using (SqlCommand cmd = new SqlCommand("GetMaxPrice", conn))
{
//将命令类型设为存储过程
cmd.CommandType = CommandType.StoredProcedure;
//添加入参
cmd.Parameters.Add(new SqlParameter("@DTypeId",
SqlDbType.Int, 18, "DTypeId"));
//添加出参
cmd.Parameters.Add(new SqlParameter("@DPrice",
SqlDbType.Int, 18, ParameterDirection.Output, false, 0, 0,
"DPrice", DataRowVersion.Default, null));
//添加返回值
cmd.Parameters.Add(new SqlParameter("@return",
SqlDbType.Int,18,ParameterDirection.ReturnValue,true,0,0,
"return",DataRowVersion.Default,null));
//给入参赋值
cmd.Parameters["@DTypeId"].Value = int.Parse(txtEnter.Text);
//执行存储过程
cmd.ExecuteNonQuery();
//获取返回值
var ret = cmd.Parameters["@return"].Value;
//获取出参
string price = cmd.Parameters["@DPrice"].Value.ToString();

if ((int)ret > 0)
{
textBox1.Text = price;
}
}
//关闭连接
conn.Close();
}
温馨提示:答案为网友推荐,仅供参考
相似回答