sql - SQL 不是由 JDBC 运行,但在数据库客户端中可以完美运行
问题描述
我有一个查询要从 SQL Server 2012 中选择树结构数据以从一个表中获取树结构结果集。
这是我使用的 SQL:
with cte_child (id, parentId, contractId, contractName, jfCompany, jfDepartment, yfDepartment, totalAmount, signDate, lvl)
as
(
select
id, parentId, contractId, contractName,
jfCompany, jfDepartment, yfDepartment, totalAmount, signDate, 0
from
Contract_info_main
where
contractId = 'c2012-0412'
union all
select
c.id, c.parentId, c.contractId, c.contractName,
c.jfCompany, c.jfDepartment, c.yfDepartment, c.totalAmount,
c.signDate, s.lvl+1
from
Contract_info_main c
inner join
cte_child s on s.parentId = c.id
)
select * from cte_child
此 SQL 语句在本地 SQL Server 2012 数据库以及我的带有 DBeaver 客户端的本地计算机上运行时结果正确。DBeaver 使用的驱动程序是“mssql-jdbc:7.4.1.jre8”。
奇怪的是,当我使用纯 Java 代码发送相同的 SQL 字符串来发送完全相同的查询时,它失败并出现错误
对象名称“Contract_inf_main”无效
由于我使用的是 Ubuntu 18,我想 DLL 和驱动程序应该不是问题?但这个问题的可能原因是什么?谢谢
这是我的 JDBC 代码:
public static void main(String[] args) throws ClassNotFoundException, SQLException {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
final Connection connection = DriverManager.getConnection("jdbc:sqlserver://192.168.5.158:1433", "general_reader", "sqlserver2017@reader");
final String sql = "with cte_child(id, parentId, contractId, contractName, jfCompany, jfDepartment, yfDepartment, totalAmount, signDate, lvl) " +
"as (select id, parentId, contractId, contractName, jfCompany, jfDepartment, yfDepartment, totalAmount, signDate, 0 " +
"from Contract_info_main where contractId = 'jy2012-041' " +
"union all select c.id, c.parentId, c.contractId, c.contractName, c.jfCompany, c.jfDepartment, c.yfDepartment, c.totalAmount, c.signDate, s.lvl+1 " +
"from Contract_info_main c inner join cte_child s on s.parentId = c.id) select * from cte_child";
final PreparedStatement statement = connection.prepareStatement(sql);
System.out.println(sql);
final ResultSet resultSet = statement.executeQuery();
while(resultSet.next()) {
System.out.println("id = " + resultSet.getString(1) + " and parentId = " + resultSet.getString(2));
}
resultSet.close();
statement.close();
connection.close();
}
解决方案
推荐阅读
- xquery - 如何在 MarkLogic 中按顺序执行条件?
- r - SparkR:无法创建 Spark 会话
- spring-data-jpa - 如何在不使用查询注释的情况下从 SpringData 中获取不同的列表?
- python - 有没有办法在 pyqt5 或 qt5 中截取窗口的屏幕截图?
- c - GNU 复杂性输出中的“ln-ct”和“nc-lns”是什么意思?
- amazon-web-services - 如何在 AWS 控制台中查找我的 AWS SES 未处于沙盒模式?
- http - 创建带有标题的 URL
- python - FLASK 提交后导致奇怪的 IntegrityError 违反唯一约束
- angularjs - 从具有动态模式的 JSON 加载,patternSourceCanvas 未定义序列化 JSON 数据返回的错误
- python - 模拟测试 api 的 post 方法