I'm trying insert into three tables, using JDBC. My code query rans well in MySQL Workbench, but when I run it using PreparedStatement
, I run into error saying
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use
My query looks like
BEGIN;
INSERT INTO user_authentication (enabled, password, username) values (1,'password','username');
SET @userId = LAST_INSERT_ID();
INSERT INTO account(is_active, balance, user_id) values(1,0.0,@userId);
INSERT INTO user_information (email, firstname, lastname, user_id) values ('OLeg@mail.com','Oleg','Oleg',@userId);
INSERT INTO user_authorization (role, user_id) values ('ROLE_USER', @userId);
COMMIT;
It seems that error is due to that BEGIN;
statement.
How can I run multiply insert query using JDBC and PreparedStatement
?
Whole method looks like
@Override
public void save(User user) {
Connection conn = null;
Account account = user.getAccount();
UserInformation information = user.getUserInformation();
Set<UserAuthorization> roles = user.getRoles();
String insertUserQuery = "INSERT INTO user_authentication (enabled, password, username) values (?,?,?);";
String insertAccountQuery = "INSERT INTO account(is_active, balance, user_id) values(?,?,@userId);";
String insertInformationQuery = "INSERT INTO user_information (email, firstname, lastname, user_id) values (?,?,?,@userId);";
String insertRolesQuery = "INSERT INTO user_authorization (role, user_id) values (?, @userId);";
String query = "BEGIN;" + insertUserQuery
+ " SET @userId = LAST_INSERT_ID(); " + insertAccountQuery
+ insertInformationQuery + insertRolesQuery + "COMMIT;";
try {
conn = dataSource.getConnection();
PreparedStatement statement = conn.prepareStatement(query);
statement.setBoolean(1, true);
statement.setString(2, user.getPassword());
statement.setString(3, user.getUsername());
statement.setBoolean(4, true);
statement.setDouble(5, account.getBalance());
statement.setString(6, information.getEmail());
statement.setString(7, information.getFirstName());
statement.setString(8, information.getLastName());
for (UserAuthorization role : roles) {
statement.setString(9, role.getRole().toString());
}
statement.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}