mariadb 如何在PreparedStatement中处理单引号?

pzfprimi  于 2022-11-08  发布在  其他
关注(0)|答案(2)|浏览(167)

我想使用一个 * 预准备语句 *,如下所示:

acl = conn.prepareStatement("INSERT INTO acls_t(user,topic,rw) values((SELECT id from users_t where username=?),'?/#',1);");
mqtt_acl.setString(1, name);
mqtt_acl.setString(2, uuid);

我的数据库是MariaDB,它不接受此错误。它返回以下错误:

java.sql.SQLException: Could not set parameter at position 2 (values was '3aa4ea54-3105-47a3-9bfb-c17c4348d84a')
Query - conn:56(M)  - "INSERT INTO acls_t(user,topic,rw) values((SELECT id from users_t where username=?),'?/#',1);"

我该怎么办?

j7dteeu8

j7dteeu81#

请按以下步骤操作:

acl = conn.prepareStatement("INSERT INTO acls_t(user,topic,rw) values((SELECT id from users_t where username=?),?,1);");
mqtt_acl.setString(1, name);
mqtt_acl.setString(2, uuid + "/#");
l2osamch

l2osamch2#

您的sql语句可以简化为:

INSERT INTO acls_t(user,topic,rw) SELECT id, CONCAT(?, '/#'), 1 FROM users_t WHERE username = ?;

而不使用必须嵌套SELECT语句的VALUES
因此,请将代码更改为:

acl = conn.prepareStatement("INSERT INTO acls_t(user,topic,rw) SELECT id, CONCAT(?, '/#'), 1 FROM users_t WHERE username = ?;");
mqtt_acl.setString(1, uuid);
mqtt_acl.setString(2, name);

在此代码中,如果username等于变量name的值的表users_t中没有用户,则不会插入行,但您的代码将尝试向表acls_t插入一行,并将列user设置为null

相关问题