V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
xuanxiao
V2EX  ›  程序员

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

  •  
  •   xuanxiao · 2022-01-25 14:30:20 +08:00 · 1129 次点击
    这是一个创建于 793 天前的主题,其中的信息可能已经有所发展或是发生改变。

    同一条 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 吗?

    8 条回复    2022-02-07 09:54:33 +08:00
    liprais
        1
    liprais  
       2022-01-25 14:33:01 +08:00
    在 subquery 里面排序有啥意义.....
    xuanxiao
        2
    xuanxiao  
    OP
       2022-01-25 14:42:25 +08:00
    @liprais 这样最终结果也是排好序的呀,为什么没有意义呢
    yuztoex
        3
    yuztoex  
       2022-01-25 15:07:28 +08:00
    我记得这个本来就不支持啊,你可以换个客户端试试看
    order by 不支持本次查询新设的 alas
    xuanxiao
        4
    xuanxiao  
    OP
       2022-01-25 15:11:05 +08:00
    @yuztoex mysql 命令行和 workbench 都是支持的,只有 jdbc 的 preparedStatement 报错
    sagaxu
        5
    sagaxu  
       2022-01-25 15:15:40 +08:00 via Android
    把 jdbc 的 strict_mode 关掉
    xuanxiao
        6
    xuanxiao  
    OP
       2022-01-25 16:31:34 +08:00
    @sagaxu jdbc 怎么关这个呀?你指的是 mysql 的 sql_mode 吗,这个默认就是关的
    seanzxx
        7
    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
        8
    xuanxiao  
    OP
       2022-02-07 09:54:33 +08:00
    @seanzxx 我又尝试了一下,发现数据库连接加上“rewriteBatchedStatements=true”这个参数之后才会报错,且只有 preparedStatement 报错。不加这个参数的话,statement 和 preparedStatement 都不会报错。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5390 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 09:11 · PVG 17:11 · LAX 02:11 · JFK 05:11
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.