[英]python sqlite3 can't execute a valid sqlite3 command
我感觉这很明显,但是当我在sqlite3中运行命令时很好,但是随后我从python sqlite3中运行了同一命令却不起作用。
架构:
sqlite> .schema transcriptionUnit
CREATE TABLE "transcriptionUnit" (
id INTEGER NOT NULL,
name VARCHAR NOT NULL,
PRIMARY KEY (id)
);
Python功能:
def getValue(path2db, tableName, columnName, findColumn, findValue):
import sqlite3
db = sqlite3.connect(path2db)
cursor = db.cursor()
query = 'SELECT '+columnName+' FROM '+tableName+' WHERE '+findColumn+' = '+findValue
print(query)
cursor.execute(query)
all_rows = cursor.fetchall()
db.close()
return all_rows
sqlite3中的命令:
sqlite> select id from transcriptionUnit where name = 'TU_001';
1
ipython中的命令:
In [13]: db_funcs.getValue('/home/oli/Dropbox/Documents/PhD/wc-model-docs/geneLabels/gene_db/gene_db.db','transcriptionUnit', 'id', 'name', 'TU_001')
---------------------------------------------------------------------------
OperationalError Traceback (most recent call last)
<ipython-input-13-1797c506d95e> in <module>()
----> 1 db_funcs.getValue('/home/oli/Dropbox/Documents/PhD/wc-model-docs/geneLabels/gene_db/gene_db.db','transcriptionUnit', 'id', 'name', 'TU_001')
/home/oli/Dropbox/Documents/PhD/wc-model-docs/geneLabels/gene_db/python/read_db_funcs.pyc in getValue(path2db, tableName, columnName, findColumn, findValue)
19 cursor = db.cursor()
20 query = 'SELECT '+columnName+' FROM '+tableName+' WHERE '+findColumn+' = '+findValue
---> 21 cursor.execute(query)
22 all_rows = cursor.fetchall()
23 db.close()
OperationalError: no such column: TU_001
只是为了表明该函数通常可以正常工作:
In [15]: db_funcs.getValue('/home/oli/Dropbox/Documents/PhD/wc-model-docs/geneLabels/gene_db/gene_db.db','transcriptionUnit', 'name', 'id', str(1))
Out[15]: [(u'TU_001',)]
现在,我的大脑已经为此思考了很长时间,因此不胜感激。
在SQL中,字符串必须用引号引起来。 您是使用sqlite3
的命令执行此操作的,但不是在Python中构建命令时执行的。
但是要避免这样的字符串格式问题(以及SQL注入攻击),请更好地使用参数(仅适用于值,不适用于表/列名):
query = 'SELECT '+columnName+' FROM '+tableName+' WHERE '+findColumn+' = ?'
cursor.execute(query, [findValue])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.