[求助] JDBC 的 statement 和 preparedStaement 执行结果不同

2022-01-25 14:30:20 +08:00
 xuanxiao

同一条 sql:

select b from( select n.id as a, n.name as b from tableX n order by a, b ) t;

在 mysql 里是能跑通的,使用 jdbc 的 statement 也能跑通,但使用 preparedStatement 就报错了:

Exception in thread "main" com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'a' in 'order clause'

这合理嘛,我要执行这种 sql 只能使用 statement 吗?

1150 次点击
所在节点    程序员
8 条回复
liprais
2022-01-25 14:33:01 +08:00
在 subquery 里面排序有啥意义.....
xuanxiao
2022-01-25 14:42:25 +08:00
@liprais 这样最终结果也是排好序的呀,为什么没有意义呢
yuztoex
2022-01-25 15:07:28 +08:00
我记得这个本来就不支持啊,你可以换个客户端试试看
order by 不支持本次查询新设的 alas
xuanxiao
2022-01-25 15:11:05 +08:00
@yuztoex mysql 命令行和 workbench 都是支持的,只有 jdbc 的 preparedStatement 报错
sagaxu
2022-01-25 15:15:40 +08:00
把 jdbc 的 strict_mode 关掉
xuanxiao
2022-01-25 16:31:34 +08:00
@sagaxu jdbc 怎么关这个呀?你指的是 mysql 的 sql_mode 吗,这个默认就是关的
seanzxx
2022-01-29 13:47:22 +08:00
要不是好奇去试一下,我就信你了。

我在本地无法重现你的问题!

MariaDB 10
MySQL Connector 8.0.28
Java 17

Table:
create table tableX(id int, name varchar(200));
insert into `tableX` values(1, 'test1');
insert into `tableX` values(2, 'test2');
insert into `tableX` values(3, 'test3');

Code:
Connection connection = DriverManager.getConnection("jdbc:mysql://test:test@localhost/test");
PreparedStatement preparedStatement =
connection.prepareStatement("select b from( select n.id as a, n.name as b from tableX n order by a, b ) t;");
ResultSet resultSet = preparedStatement.executeQuery();

while(resultSet.next()) {
System.out.println(resultSet.getString("b"));
}

Output:
test1
test2
test3
xuanxiao
2022-02-07 09:54:33 +08:00
@seanzxx 我又尝试了一下,发现数据库连接加上“rewriteBatchedStatements=true”这个参数之后才会报错,且只有 preparedStatement 报错。不加这个参数的话,statement 和 preparedStatement 都不会报错。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/830498

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX