Java SQL Server 异常:使用 JDBC 时“列名 xxx 无效”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2110757/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 03:38:29  来源:igfitidea点击:

SQL Server Exception: "The column name xxx is not valid" when using JDBC

javasql-serverjdbc

提问by Kevin Stembridge

I'm getting a strange error from the SQL Server JDBC driver. It is telling me that a column name is invalid even though the column is present, correctly named and the same query works fine when executed in SqlServer Management Studio.

我从 SQL Server JDBC 驱动程序收到一个奇怪的错误。它告诉我,即使列存在、正确命名并且在 SqlServer Management Studio 中执行时相同的查询工作正常,列名也是无效的。

The error is:

错误是:

Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: The column name MarginCall is not valid.
    at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(SQLServerException.java:170)
    at com.microsoft.sqlserver.jdbc.SQLServerResultSet.findColumn(SQLServerResultSet.java:626)
    at com.microsoft.sqlserver.jdbc.SQLServerResultSet.getBigDecimal(SQLServerResultSet.java:2570)
    at org.apache.commons.dbcp.DelegatingResultSet.getBigDecimal(DelegatingResultSet.java:305)
...

采纳答案by Kevin Stembridge

Problem solved. It was a simple mistake by me.

问题解决了。这是我的一个简单错误。

My query was using an 'AS' clause in the select statement. I was trying to retrieve the column value from the ResultSet using the actual column name, instead of the column alias defined in the AS clause.

我的查询在 select 语句中使用了“AS”子句。我试图使用实际的列名而不是 AS 子句中定义的列别名从 ResultSet 中检索列值。

Schoolboy error. Apologies for the time wasting.

小学生错误。为浪费时间道歉。

Many thanks to Steve B. for his suggestion to use ResultSet.getColumnNames(). Although the actual method call I used was ResultSet.getMetaData().getColumnName(columnIndex);

非常感谢 Steve B. 建议使用 ResultSet.getColumnNames()。虽然我使用的实际方法调用是 ResultSet.getMetaData().getColumnName(columnIndex);

回答by David Espart

Try to enclose the column name inside square brackets: [MarginCall] Just a guess.

尝试将列名括在方括号内: [MarginCall] 只是猜测。

回答by Mauricio

Check the case of your table name. if collation is set to case sensitive on ms sql server the table names are affected too.

检查表名的大小写。如果排序规则在 ms sql server 上设置为区分大小写,则表名也会受到影响。