MySQL例外:执行SQL事务

时间:2012-11-03 19:53:27

标签: mysql playframework-2.0 anorm

我正在尝试向MySQL提交一个sql事务,但我已经过了MySQLSyntaxErrorException

我使用的代码是:

implicit connection => 
        SQL("""
            start transaction;
            insert into projects(id_user, name, description) values({idUser}, {name}, {description});
            set @last_id = last_insert_id();
            insert into assigned(id_user, id_project) values({idUser}, @last_id);
            commit;
        """)
    .on('idUser -> idUser,
        'name -> project.name,
        'description -> project.description
    ).execute()  

我得到的例外:

[MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'insert into projects(id_user, name, description) values(1, 'First inserted proje' at line 1]  

我开始认为我无法使用Anorm执行此类声明。

1 个答案:

答案 0 :(得分:2)

您不能以这种方式使用交易。您必须了解anorm只是现有jdbc库的包装器。默认情况下,使用 withConnection SQL 时:

DB.withConnection { conn => 
    SQL("...
}

使用PreparedStatement转换您的查询。意味着;字符导致错误。

因此,如果您想使用事务,则必须使用anorm's mecanism

DB.withTransaction { conn =>
    SQL("...
}