gpt4 book ai didi

java - executeUpdate() 不添加字符串变量

转载 作者:行者123 更新时间:2023-12-01 16:54:46 24 4
gpt4 key购买 nike

我创建了这样的声明:

String query = "INSERT INTO ZMONES (ID, PAVADINIMAS, SLAPTAZODIS) VALUES("
+sum+" ,"+a+", "+b+")";

其中变量 sum 是数据库表中的整数 ID,a 和 b 是要相加的两个字符串值。我正在执行此语句:stmt.executeUpdate(query);

但是弹出此错误:

Column 'PERSON' is either not in any table in the FROM list or appers within a join specification and is outside the scope of the join specification or appears in a having clause and is not in the GROUP BY list. If this is a CREATE or ALTER TABLE statement then 'PERSON' is not a column in the target table.

我确实知道Java将其解释为列的名称,但是我不明白为什么会发生这种情况?我在 stackoverflow 中搜索过这个问题,大多数问题都涉及文本而不是字符串变量。

最佳答案

您遇到的错误可以轻松纠正,如下所示(假设 sum 是一个数字):

String query = "INSERT INTO ZMONES (ID, PAVADINIMAS, SLAPTAZODIS) VALUES("
+sum+" ,'"+escape(a)+"', '"+escape(b)+"')";

其中 escape(String) 是以下方法:

public String escape(String string) {
// This works in most databases, although some require you to escape apostrophes via \'
return string == null ? null : string.replace("'", "''");
}

关于 SQL 注入(inject)的说明

但是拜托了!不要那样做。使用 PreparedStatement 和适当的绑定(bind)变量,而不是将输入连接到 SQL 语句中。为什么?

方法如下:

try (PreparedStatement s = connection.prepareStatement(
"INSERT INTO ZMONES (ID, PAVADINIMAS, SLAPTAZODIS) VALUES (?, ?, ?)")) {
s.setInt(1, sum);
s.setString(2, a);
s.setString(3, b);
s.executeQuery();
}

关于java - executeUpdate() 不添加字符串变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34707222/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com