列名称包含下划线时的语法错误 [英] Syntax Error when the column name contains underscore

查看:119
本文介绍了列名称包含下划线时的语法错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以编译但无法执行以下代码
,并出现错误(使用Postgres):

I can compile but can't execute 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.

对于MySQL,请使用反引号。

For MySQL, use backticks.

select `20_5` as name from flowshop_optimums

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

For SQL Server, use square brackets.

select [20_5] as name from flowshop_optimums

对于PostgreSQL,请使用双引号。

For PostgreSQL, use double quotes.

select "20_5" as name from flowshop_optimums

这篇关于列名称包含下划线时的语法错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆