您现在的位置是:首页 >技术教程 >C# Dapper中调用存储过程和执行事物网站首页技术教程
C# Dapper中调用存储过程和执行事物
using (DbConnection db = new SqlConnection(sqlConnectstr))
{
//不带参数的存储过程
List<StuInfo> listStuInfo = new List<StuInfo>();
listStuInfo = db.Query<StuInfo>("P_stuMarkInfo", null, null, true, null, CommandType.StoredProcedure).ToList();
if (listStuInfo.Count > 0)
{
listStuInfo.ForEach((stu) => this.textBox1.Text += stu.StuName + " ");
}
//带参数的存储过程
var p = new DynamicParameters();//动态参数类
p.Add("@w", int.Parse(txtw.Text));
p.Add("@l", int.Parse(txtL.Text));
p.Add("@countNum", 0, DbType.Int32, ParameterDirection.Output);
db.Execute("P_stuMarkInfo1", p, null, null, CommandType.StoredProcedure);
int countNum = p.Get<Int32>("@countNum");
txtCountNum.Text = countNum.ToString();
db.Open();
//执行事务
IDbTransaction tran = db.BeginTransaction();
try
{
string sqlDel1 = " delete from stumark where stuno=@stuNo";
string sqlDel2 = " delete from stuinfo where stuno=@stuNo";
db.Execute(sqlDel1, new { stuNo = "1001" }, tran, null, null);
db.Execute(sqlDel2, new { stuNo = "1001" }, tran, null, null);
tran.Commit();
MessageBox.Show("删除成功");
}
catch (Exception ex)
{
tran.Rollback();
MessageBox.Show("删除失败", ex.Message);
db.Close();
}
finally
{
db.Close();
}
}