列名包含下划线时出现语法错误

时间:2011-06-08 13:59:17

标签: sql postgresql

我可以编译但不能执行以下代码 错误(使用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

4 个答案:

答案 0 :(得分:5)

这不是下划线,而是列名以数字开头。你需要逃避这一点。

对于MySQL,请使用反引号。

select `20_5` as name from flowshop_optimums

对于SQL Server,请使用方括号。

select [20_5] as name from flowshop_optimums

对于PostgreSQL,请使用双引号。

select "20_5" as name from flowshop_optimums

答案 1 :(得分:1)

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

但你应该真的更改该列名。

答案 2 :(得分:0)

试试这个:results = query.executeQuery(“选择'20_5'作为来自flowshop_optimums的名字”);

答案 3 :(得分:0)

你需要用反引号或括号括起20_5,具体取决于你是否分别使用MySQL或SQLServer。