You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在SQL中转义含斜杠的表名(如Value123/123)

Problem Extracting Values from SQL Table with Special Characters in Column Name

The Issue

When trying to pull values from a SQL table where a column name includes a slash (like Value123/123), you’ll run into syntax errors or unexpected behavior. For example, the code below throws an error right at the line trying to access that column:

cursor = conn.cursor()
cursor.execute("select Test, Value123/123 from db")
Test = []
Value = []
Compiled_Dict = {}
for row in cursor:
    Test.append(row.Test)
    Value.append(row.Value123/123)  # Error triggers here
Compiled_Dict = {'Date&Time': Test}
Compiled_Dict['Value'] = Value
conn.close()
df = pd.DataFrame(Compiled_Dict)

The error will say something like "no column named 'Value123' exists"—and that’s because Python interprets the slash / as a division operator. Instead of targeting the full column name Value123/123, it tries to take row.Value123 and divide it by 123, which fails because there’s no Value123 column.

Even if you try defining a variable like x='Value123/123' and appending that, you’ll only get the string literal instead of the actual database value from the column.

The Fix

The cleanest solution is to use an alias for the problematic column directly in your SQL query. By renaming the column to something without special characters using as, you can easily access it in Python without syntax conflicts.

Here’s the modified, working code:

cursor = conn.cursor()
# Add an alias "newValue" for the column with the slash
cursor.execute("select Test, Value123/123 as newValue from db")
Test = []
Value = []
Compiled_Dict = {}
for row in cursor:
    Test.append(row.Test)
    Value.append(row.newValue)  # Use the alias to access the column value
Compiled_Dict = {'Date&Time': Test}
Compiled_Dict['Value'] = Value
conn.close()
df = pd.DataFrame(Compiled_Dict)

Alternative Approach

If you don’t want to use an alias for some reason, you can also access the column by its index position in the result set. Since Value123/123 is the second column in your SELECT statement, you’d use row[1] instead:

Value.append(row[1])

That said, using an alias is generally better for readability—anyone looking at your code can immediately tell what row.newValue refers to, whereas row[1] becomes ambiguous if you ever adjust the order of columns in your query.

内容的提问来源于stack exchange,提问作者flamingbird123

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 06:53:42