Issue
I've a stupid problem that I cannot resolve. I'm learning Java and I'm new with this. My case is:
// ad a person into db
public static void aggiungiPersona(int id, String nome, String cognome, int anni, String sesso,
String indirizzo, String numTel, String email) {
try {
// create query
String query = String.join("", "insert into persone (id, nome, cognome, anni, sesso, indirizzo, numTel, email) VALUES (",
Integer.toString(id), ", '",
nome, "', '",
cognome, "', ",
Integer.toString(anni), ", '",
sesso, "', '",
indirizzo, "', '",
numTel, "', '",
email, "', ",
")"
);
I know that the problem is in quotes or double quotes, but where?
Solution
You should be using a prepared statement here which handles the proper escaping of your literal value:
String sql = "INSERT INTO persone (id, nome, cognome, anni, sesso, indirizzo, numTel, email) ";
sql += "VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, Integer.toString(id)); // use ps.setInt(1, id) if id be integer column
ps.setString(2, nome);
ps.setString(3, cognome);
ps.setString(4, Integer.toString(anni)); // use ps.setInt(4, anni) for anni integer column
ps.setString(5, sesso);
ps.setString(6, indirizzo);
ps.setString(7, numTel);
ps.setString(8, email);
int row = ps.executeUpdate();
System.out.println(row);
Answered By - Tim Biegeleisen