【问题标题】:SQLException: Incorrect syntax near 'bit'SQLException:“位”附近的语法不正确
【发布时间】:2016-01-09 14:46:57
【问题描述】:

我已经使用 JDBC 连接到 SQL Server。我运行的查询之一具有数据类型位,当我运行程序时出现此错误:SQLException: Incorrect syntax near 'bit'。

这是我的代码:

            String sql3 = "SELECT DISTINCT customCategoryDescription FROM product_categories ORDER BY customCategoryDescription";
        rs2 = stmt3.executeQuery(sql3);

        while (rs2.next())
        {
            String customCategoryDescription = rs2.getString("customCategoryDescription");
            columns.add(customCategoryDescription);
        }
        rs2.close();
        stmt3.close();

        for(int i = 0; i < columns.size(); i++)
        {
            String sql4 = "ALTER TABLE transformed_table ADD "+columns.get(i)+" bit";
            stmt4.executeUpdate(sql4);
            stmt4.close();
        }

我在 SQL Server 中尝试了相同的查询,并成功添加了列。

问题出在哪里?

【问题讨论】:

  • 您应该编辑您的问题并在变量替换后打印出sql4
  • @GordonLinoff ALTER TABLE encrypted_table ADD B2B 解决方案位 也许问题是因为空格字符。但是我怎样才能删除它呢?
  • 如果列名中有空格,请将列放在方括号之间。

标签: java sql-server jdbc


【解决方案1】:

我的猜测是您在 customCategoryDe​​scription 中有一个无效列名的值——例如“NO SPACES”,这意味着:

String sql4 = "ALTER TABLE transformed_table ADD "+columns.get(i)+" bit";

会生成这个:

ALTER TABLE transformed_table ADD NO SPACE bit;

如果你这样做(注意 [ 和 ] ):

String sql4 = "ALTER TABLE transformed_table ADD ["+columns.get(i)+"] bit";

ALTER TABLE transformed_table ADD [NO SPACE] bit;

【讨论】:

  • 我能再问你一个问题吗?我想运行这些查询: String sql9 = SELECT 1 FROM transactions AS tr, product_categories AS pc WHERE payer_id = "+payer_ids.get(i)+" AND customCategoryDescription = ["+columns.get(j)+"] AND tr.id_3rd_level = pc.id_3rd_level;字符串 sql10 = INSERT INTO transformed_table (["+columns.get(j)+"]);但我收到此错误但我收到此消息:SQLException: Invalid column name 'B2B Solutions'。你能帮帮我吗?
  • @KonstantinaPapagiannopoulou - 这个问题已经得到解答。如果您还有其他问题,请ask a new question。您始终可以在新问题中包含 link to this question 以提供上下文。
  • 您的 SELECT 语句最像这样生成:AND customCategoryDescription = [B2B Solutions] 但您希望 [B2B 解决方案] 使用单引号而不是方括号呈现。 (因为在这种情况下,您引用的是字符值而不是原始问题中的列名:AND customCategoryDescription = 'B2B Solutions'
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-11-09
  • 2021-01-23
  • 2011-05-28
  • 2020-11-03
  • 2019-04-13
  • 1970-01-01
  • 2010-11-27
相关资源
最近更新 更多