我用MySql.Data设置的事务总是不起作用,无法回滚,代码如下:
用Dapper的Excecute也不行
[code=csharp] var now = (int)Function.GetTimeSpan().TotalSeconds;
using (var conn = DbHelper.GetMySqlConnection())
{
conn.Open();
var trans = conn.BeginTransaction();
try
{
StringBuilder sql = new StringBuilder();
sql.Append(" INSERT INTO dg_article(");
sql.Append(" typeid, title, listorder, seokeywords, seodescription, body, addtime,");
sql = new StringBuilder(sql.ToString().TrimEnd(','));
sql.Append(" ) VALUES (");
sql.Append(" @Typeid, @Title, @Listorder, @Seokeywords, @Seodescription, @Body, @Addtime,");
sql = new StringBuilder(sql.ToString().TrimEnd(','));
sql.Append(")");
var item = new DgArticle
{
Addtime = now,
Body = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
Listorder = 0,
Seodescription = "",
Seokeywords = "",
Title = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
Typeid = 1
};
//var rows = Tools.ToInt(conn.Execute(sql.ToString(), item, trans));
var rows = Tools.ToInt(SqlMapper.Execute(conn, sql.ToString(), item, trans, null, null));
if (rows > 0)
{
sql.Clear();
sql.Append(" INSERT INTO dg_about (title, seokeywords, seodescription, listorder, body) VALUES (@title, @seokeywords, @seodescription, @listorder, @body, )"); //这个地方故意写错,让事务进行回滚
var ab = new DgAbout
{
Body = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
Listorder = 0,
Seodescription = "",
Seokeywords = "",
Title = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
};
rows = conn.Execute(sql.ToString(), ab, trans);
trans.Commit();
return true;
}
else
{
trans.Rollback();
return false;
}
}
catch (Exception ex)
{
trans.Rollback();
Record.Write(className, "Add", ex.Message);
return false;
}
}[/code]
同样的写法换成Sql Server数据库就没有问题