开发者

Syntax Error when the column name contains underscore

I can compile but can't e开发者_StackOverflow社区xecute the following code with the error (using Postgres):

Fatal database error
ERROR: syntax error at or near "as"
Position: 13

import java.sql.*;
public class JDBCExample
{
private static final String JDBC_DRIVER = "org.postgresql.Driver";
private static final String URL = "jdbc:postgresql://hostname/database";
private static final String USERNAME = "username";
private static final String PASSWORD = "password";

public static void main(String[] args) throws Exception
{
  Connection dbConn = null;
  Statement query = null;
  ResultSet results = null;

  Class.forName(JDBC_DRIVER);

  try
  {
     dbConn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
  }
  catch (SQLException e)
  {
     System.out.println("Unable to connect to database\n"+e.getMessage());
     System.exit(1);
  }

  try
  {
     query = dbConn.createStatement();
     results = query.executeQuery("select 20_5 as name from flowshop_optimums");

    while (results.next())
    {
      System.out.println(results.getString("name"));
    }

    dbConn.close();
  }
  catch (SQLException e)
  {
     System.out.println("Fatal database error\n"+e.getMessage());
     try
     {
        dbConn.close();
     }
     catch (SQLException x) {}
     System.exit(1);
  }

} // main

} // Example


It's not the underscore, it's the fact that the column name starts with a number. You'd need to escape this.

For MySQL, use backticks.

select `20_5` as name from flowshop_optimums

For SQL Server, use square brackets.

select [20_5] as name from flowshop_optimums

For PostgreSQL, use double quotes.

select "20_5" as name from flowshop_optimums


results = query.executeQuery("select \"20_5\" as name from flowshop_optimums");

But you should really change that column name.


Try this: results = query.executeQuery("select '20_5' as name from flowshop_optimums");


You need to enclose 20_5 with backticks or brackets, depending on whether or not you're using MySQL or SQLServer, respectively.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜