Python SQLite3 无法执行有效的 sqlite3 命令



我觉得这很明显,但是当我在sqlite3中运行命令时,这很好,但是然后我从python sqlite3运行相同的命令,它不起作用。

图式:

sqlite> .schema transcriptionUnit
CREATE TABLE "transcriptionUnit" (
    id INTEGER NOT NULL,
    name VARCHAR NOT NULL,
    PRIMARY KEY (id)
);

蟒蛇函数:

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])

最新更新