我想使用 Python 和 sqlite3 在 Jupyter Notebook 上的数据库中创建一个表。 为了避免表已存在错误,我使用了以下代码:
q1 = '''
CREATE TABLE IF NOT EXISTS person (
person_id TEXT PRIMARY KEY,
first_name TEXT,
last_name TEXT
);
'''
run_query(q1)
但是我收到了此错误,我无法摆脱它。
TypeErrorTraceback (most recent call last)
<ipython-input-25-948d42611e56> in <module>()
7
8 '''
----> 9 run_query(q1)
<ipython-input-13-67c680d27fbe> in run_query(q)
3 def run_query(q):
4 with sqlite3.connect(db) as conn:
----> 5 return pd.read_sql(q,conn)
6
7 def run_command(c):
/dataquest/system/env/python3/lib/python3.4/site-packages/pandas/io/sql.py in read_sql(sql, con, index_col, coerce_float, params, parse_dates, columns, chunksize)
398 sql, index_col=index_col, params=params,
399 coerce_float=coerce_float, parse_dates=parse_dates,
--> 400 chunksize=chunksize)
401
402 try:
/dataquest/system/env/python3/lib/python3.4/site-packages/pandas/io/sql.py in read_query(self, sql, index_col, coerce_float, params, parse_dates, chunksize)
1443 args = _convert_params(sql, params)
1444 cursor = self.execute(*args)
-> 1445 columns = [col_desc[0] for col_desc in cursor.description]
1446
1447 if chunksize is not None:
TypeError: 'NoneType' object is not iterable
该表是在我检查时创建的,并且列在那里。
任何帮助将不胜感激。
run_query()
使用创建的read_sql()
从数据库中读取行,而不是创建表或插入行。read_sql()
期望查询将从数据库中获取行,并尝试迭代这些行,但CREATE
返回None
- 你会得到'NoneType' object is not iterable
您应该直接使用execute(query)
- 即。
with sqlite3.connect(db) as conn:
conn.execute(q1)