java - 查询问题——JDBC中插入(双引号、单引号)

标签 java sql eclipse jdbc

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

相关文章:

android - 执行 aapt 时出错 : Cannot run program, CreateProcess error=5,访问被拒绝 : CreateProcess error=5, 访问被拒绝

java - Scala:从返回 Seq 的函数返回可变缓冲区

java - 如何对字符串进行编码和解码以便在查询字符串中使用?

sql - Postgres 选择时间范围前后是否存在另一个事件

java - JScrollPane 在 JTextArea 中表现得很奇怪

java - 错误: Could not find or load main class

java - Android - 架构决策

java - 如何让数组中的所有卡片都显示出来?

c# - 无法从 C# 将数据存储在 SQL Server 中

sql - 如何获取每个用户的第一个条目(包括条目 ID)