英文:
Query problem - insert in JDBC (double quotes, single quote)
问题
我有一个解决不了的愚蠢问题。我正在学习Java,对此还不熟悉。我的情况是:
// 将一个人添加到数据库中
public static void aggiungiPersona(int id, String nome, String cognome, int anni, String sesso,
String indirizzo, String numTel, String email) {
try {
// 创建查询
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'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?
答案1
得分: 2
你应该在这里使用一个预处理语句来处理正确的转义文本值:
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)); // 如果 id 是整数列,请使用 ps.setInt(1, id)
ps.setString(2, nome);
ps.setString(3, cognome);
ps.setString(4, Integer.toString(anni)); // 如果 anni 是整数列,请使用 ps.setInt(4, anni)
ps.setString(5, sesso);
ps.setString(6, indirizzo);
ps.setString(7, numTel);
ps.setString(8, email);
int row = ps.executeUpdate();
System.out.println(row);
英文:
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);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论