【发布时间】:2016-03-26 03:40:59
【问题描述】:
我有一个 sqlite 数据库,其中包含多个表的视图,其中包含许多列名称中带有空格的列(我知道,我知道,这不是好的做法,但它超出了我的控制范围)。
无论如何,我遇到的问题与使用pd.read_sql('SELECT "stupid column with space" from StupidView',con=db) 时列名中的空格有关。 它在查询视图时保留列名中的引号,但在查询表本身时不保留! 表上的相同 SQL 返回列而不用引号括起来。我在这里错过了什么吗?关于为什么会发生这种情况的任何想法?
独立工作示例:
import pandas as pd
import sqlite3
import numpy as np
pd.set_option('display.width', 1000)
# Create the database
db = sqlite3.connect("Sample Database.sqlite")
cursor = db.cursor()
# Create a table
df = pd.DataFrame({"Stupid column with space":[1,2,3,4],
"MrNoSpace":[1,2,3,4]})
# Push the tables to the database
df.to_sql(name="StupidTable", con=db, flavor='sqlite', if_exists='replace', index=False)
# Just in case you're running this more than once, drop the view if it exists
try: cursor.execute("DROP VIEW StupidView;")
except: pass
# Execute the sql that creates the view
cursor.execute("""
CREATE VIEW StupidView AS
SELECT StupidTable.*
FROM StupidTable""")
db.commit()
# Execute the SQL and print the results
Test1_df = pd.read_sql('SELECT "Stupid column with space", "MrNoSpace" FROM StupidView',con=db) # read data from the view
Test2_df = pd.read_sql('SELECT "Stupid column with space", "MrNoSpace" FROM Table1',con=db) # same sql but on the table
Test3_df = pd.read_sql('SELECT `Stupid column with space`, `MrNoSpace` FROM StupidView',con=db) # using ` and not "
Test4_df = pd.read_sql('SELECT [Stupid column with space], [MrNoSpace] FROM StupidView',con=db) # using []
print Test1_df
print Test2_df
print Test3_df
print Test4_df
输出:
Test1_df - 视图上的查询:列用双引号括起来
"Stupid column with space" "MrNoSpace"
0 1 1
1 2 2
2 3 3
3 4 4
Test2_df - 相同的查询,但在表格上:现在列名中没有引号
Stupid column with space MrNoSpace
0 1 1
1 2 2
2 3 3
3 4 4
Test3_df - 将列名包含在 ` 中(如果查询是针对表而不是视图,则可以正常工作)
`Stupid column with space` `MrNoSpace`
0 1 1
1 2 2
2 3 3
3 4 4
Test4_df - 完全删除列名(如果用于表而不是视图,则可以正常工作)
0 1 1
1 2 2
2 3 3
3 4 4
【问题讨论】:
-
它对我来说始终如一(Windows 7 64 位上的 Python 3.5.1)——所有 4 个变体都没有引号(就像在你的
Test2_df案例中一样) -
有趣...我在 Python 2.7.11 (Pandas 0.18.0) 上。听起来像一个 python 问题。
-
我刚刚在 Python 2.7.11 上测试了它,我遇到了和你一样的问题
-
所以它看起来像是一个 sqlite 问题:
print cursor.execute('SELECT "Stupid column with space", "MrNoSpace" FROM StupidView').description和print cursor.execute('SELECT "Stupid column with space", "MrNoSpace" FROM Table1').description -
你是对的:我的 Python 2.7.11 的
sqlite3模块使用sqlite3.sqlite_version: 3.6.21 和 Python 3.5.1sqlite3.sqlite_version: 3.8.11