2011-06-08 61 views
2

我可以編譯,但不能執行下面的錯誤代碼 (使用的是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 

回答

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 
+0

對於反引號,我得到:致命數據庫錯誤錯誤:語法錯誤處於或接近「'」位置:13.括號也是如此。 – 2011-06-08 14:18:55

+0

@ Oleksandr:你使用的是什麼RDBMS? – 2011-06-08 14:20:01

+0

使用PostgreSQL。 – 2011-06-08 14:20:28

0

試試這個:results = query.executeQuery(「select'20_5'as name from flowshop_optimums」);

+0

我試過這個,但它沒有選擇命名列,而是輸出20_5幾次。 – 2011-06-08 14:05:04

+0

20_5是你選擇的。如果您希望列的名稱爲20_5,則需要「從flowshop_optimums中選擇」某個值爲20_5「。 – 2011-06-08 15:01:58

+0

我的意思是這個專欄的名字是20_5。我想從中選擇數值。 – 2011-06-08 15:03:50

0

您需要用反引號或括號括起20_5,這取決於您是否分別使用MySQL或SQLServer。

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

,但你應該真的改變該列名。