I'm new to java and for an exam, I have to make an app that's a store for a book shop but I'm having problems with the database part of the app: my prepared statement isn't working while if I copy the query generated from it and paste it into phpMyAdmin it works perfectly.
The error the app is giving me is:
java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'SET @address = LAST_INSERT_ID(); INSERT INTO utenti (email, password, nome, cogn' at line 1
The method that generates the error
public static void createUser(String email, String password, String nome, String cognome, long telefono, String indirizzo, int cap, String città) throws Exception{
Connection conn = MysqlConnection.getConnection();
try{
st = conn.prepareStatement("INSERT INTO indirizzi (indirizzo, cap, città) "
+ "VALUES (?,?,?); "
+ "SET @address = LAST_INSERT_ID(); "
+ "INSERT INTO utenti (email, password, nome, cognome, telefono, idindirizzo) "
+ "VALUES (?, ?, ?, ?, ?, @address);");
st.setString(1, indirizzo);
st.setInt(2, cap);
st.setString(3, città);
st.setString(4, email);
st.setString(5, password);
st.setString(6, nome);
st.setString(7, cognome);
st.setLong(8, telefono);
System.out.println(st);
st.executeUpdate();
}
catch(Exception e){
throw e;
}
finally{
try{
conn.close();
}
catch(SQLException e){
throw e;
}
}
}
The method where it's used (just a test method to see if the other one works)
private static void createUser()
{
try {
ModelUser.createUser("a@a.com", "qwertyasdfg", "Aldo", "Simone", 391234567890l, "via dietro 1/g", 37051, "Sì");
} catch (Exception e) {
e.printStackTrace();
}
}
The generated sql
INSERT INTO indirizzi (indirizzo, cap, città) VALUES ('via dietro 1/g',37051,'Sì'); SET @address = LAST_INSERT_ID(); INSERT INTO utenti (email, password, nome, cognome, telefono, idindirizzo) VALUES ('a@a.com', 'qwertyasdfg', 'Aldo', 'Simone', 391234567890, @address);
A little edited for readability
INSERT INTO indirizzi (indirizzo, cap, città)
VALUES ('via dietro 1/g',37051,'Sì');
SET @address = LAST_INSERT_ID();
INSERT INTO utenti (email, password, nome, cognome, telefono, idindirizzo)
VALUES ('a@a.com', 'qwertyasdfg', 'Aldo', 'Simone', 391234567890, @address);
I think that this should be working since the query itself is working when it's put into phpMyAdmin