我有一个无法解决的愚蠢问题。我正在学习 Java,对此我是新手。我的情况是:
//将一个人添加到数据库
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, "', ",
")"
);
我知道问题出在引号或双引号中,但是在哪里?
最佳答案
您应该在此处使用准备好的语句来处理文字值的正确转义:
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);
关于java - 查询问题——JDBC中插入(双引号、单引号),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64151808/