【问题标题】:Query problem - insert in JDBC (double quotes, single quote)查询问题——在JDBC中插入(双引号、单引号)
【发布时间】:2021-01-16 23:10:29
【问题描述】:

我有一个无法解决的愚蠢问题。我正在学习 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, "', ",
                 ")"

                );    

我知道问题出在引号或双引号中,但是在哪里?

【问题讨论】:

  • 您可能需要打印查询以查看其外观。
  • 请了解准备好的语句并使用它们。永远不要将值连接到查询字符串中,这会使您的代码容易受到 SQL 注入的攻击。无论如何,您的问题不在于引号,而在于尾随逗号。
  • @Arnaud 是对的。打印查询值,尝试使用数据库工具执行它并读取错误。 (顺便说一句,我认为该错误与电子邮件后的最后一个, 有关)
  • 好的,这是最后一个逗号,非常感谢!

标签: java sql eclipse jdbc


【解决方案1】:

您应该在这里使用准备好的语句来处理您的文字值的正确转义:

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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-24
    • 2011-03-09
    • 2019-07-20
    • 2023-03-25
    • 2012-10-14
    相关资源
    最近更新 更多