Question

I am trying to commit a sql transaction to MySQL but I get myself past an MySQLSyntaxErrorException.

The code I am using is:

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()  

The exception I get:

[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]  

I am starting to think that I can't execute such statements at all with Anorm.

Was it helpful?

Solution

You cannot use transaction that way. You have to understand that anorm is simply a wrapper around existing jdbc libraries. By default, when using the withConnection and SQL :

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

Your query is transformed using a PreparedStatement. Meaning the ; chars are causing errors.

Thus, if you want to use transaction, you have to use anorm's mecanism for that.

DB.withTransaction { conn =>
    SQL("...
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top