Python psycopg2 SELECT return None
Python psycopg2 SELECT return None
我尝试在我的 python 脚本中使用 psycog2。
我在 db.py
文件中有一个 get_db()
函数(我需要在 sqlite 和 psql 之间做出选择):
def get_db():
if 'db' not in g:
info_db = getDatabaseType()
if info_db['type'] != 'pgsql': # If wrong type is setup, use sqlite by default
g.db = sqlite3.connect(
current_app.config['DATABASE'],
detect_types=sqlite3.PARSE_DECLTYPES
)
g.db.row_factory = sqlite3.Row
else:
conn = psycopg2.connect(
"dbname=" + info_db['db'] +
" user=" + info_db['user'] +
" password=" + info_db['pwd'])
conn.autocommit = True
g.db = conn.cursor()
return g.db
这是在 auth.py
文件中创建 select 的代码(与 db.py
相同级别):
def load_logged_in_user():
user_id = session.get('user_id')
if user_id is None:
g.user = None
else:
db = get_db()
tes = db.execute('SELECT * FROM users')
users = tes.fetchall()
我有以下错误:
AttributeError: 'NoneType' object has no attribute 'fetchall'
如果我在 db.py
文件中执行相同的命令,它就会工作。
有什么想法吗?
提前致谢
问题在这里:
tes = db.execute('SELECT * FROM users')
users = tes.fetchall()
db.execute
returns None 分配给 tes
.
您需要做的:
db.execute('SELECT * FROM users')
users = db.fetchall()
游标执行命令然后你从游标中获取。
我尝试在我的 python 脚本中使用 psycog2。
我在 db.py
文件中有一个 get_db()
函数(我需要在 sqlite 和 psql 之间做出选择):
def get_db():
if 'db' not in g:
info_db = getDatabaseType()
if info_db['type'] != 'pgsql': # If wrong type is setup, use sqlite by default
g.db = sqlite3.connect(
current_app.config['DATABASE'],
detect_types=sqlite3.PARSE_DECLTYPES
)
g.db.row_factory = sqlite3.Row
else:
conn = psycopg2.connect(
"dbname=" + info_db['db'] +
" user=" + info_db['user'] +
" password=" + info_db['pwd'])
conn.autocommit = True
g.db = conn.cursor()
return g.db
这是在 auth.py
文件中创建 select 的代码(与 db.py
相同级别):
def load_logged_in_user():
user_id = session.get('user_id')
if user_id is None:
g.user = None
else:
db = get_db()
tes = db.execute('SELECT * FROM users')
users = tes.fetchall()
我有以下错误:
AttributeError: 'NoneType' object has no attribute 'fetchall'
如果我在 db.py
文件中执行相同的命令,它就会工作。
有什么想法吗?
提前致谢
问题在这里:
tes = db.execute('SELECT * FROM users')
users = tes.fetchall()
db.execute
returns None 分配给 tes
.
您需要做的:
db.execute('SELECT * FROM users')
users = db.fetchall()
游标执行命令然后你从游标中获取。