sqlite3 Select语句在Python中不起作用

时间:2018-12-19 03:47:12

标签: python select sqlite

我有一个sqlite3数据库,该数据库是通过.sql文件中的以下CREATE语句创建的:

create.sql

CREATE TABLE dogs (id INTEGER PRIMARY KEY, 
                   name TEXT, 
                   age INTEGER, 
                   gender CHAR(1), 
                   breed TEXT, 
                   temperament TEXT, 
                   hungry BOOLEAN);

并通过.sql文件中的INSERT语句将以下数据作为种子:

insert.sql

INSERT INTO dogs (name, age, gender, breed, temperament, hungry) VALUES
                 ("Snoopy", 3, "M", "beagle", "friendly", 1),
                 ("McGruff", 10, "M", "bloodhound", "aware", 0),
                 ("Scooby", 6, "M", "great dane", "hungry", 1),
                 ("Little Ann", 5, "F", "coonhound", "loyal", 0),
                 ("Pickles", 13, "F", "black lab", "mischievous", 1),
                 ("Clifford", 4, "M", "big red", "smiley", 1),
                 ("Lassie", 7, "F", "collie", "loving", 1),
                 ("Snowy", 8, "F", "fox terrier", "adventurous", 0),
                 (NULL, 4, "M", "golden retriever", "playful", 1);

我有一个Python Jupyter笔记本,在其中执行以下操作来创建和填充数据库“ pets.db”:

import sqlite3
connection = sqlite3.connect('pets.db')

cursor = connection.cursor()

file = open("./create.sql", 'r')
create_sql = file.read()
cursor.executescript(create_sql)

file1 = open("./insert.sql", 'r')
insert_sql = file1.read()
cursor.executescript(insert_sql)

然后我有一个名为'selects.py'的Python函数文件,用于存储SQL select语句。如下所示,第一个用于返回表中所有母狗的名称和品种。

def sql():
    return "SELECT name, breed FROM dogs WHERE gender = 'F';"

然后我尝试在Jupyter中运行以上功能:

from selects import sql
cursor.execute(sql()).fetchall()

我收到以下错误:

NameError: name 'f' is not defined

过去一个小时,我一直在尝试以一种可以在Python文件中使用的方式来格式化select语句,但是每次都会很短。是SQL SELECT语句的编写方式不正确,还是采用Python代码格式?

编辑:这是完整的回溯:

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-87-df843ecc4fb9> in <module>()
      1 from selects import sql
----> 2 cursor.execute(sql())
      3 results = cursor.fetchall()
      4 results

~/ds-practice/selects.py in sql()
      1 def sql():
----> 2     return "SELECT name, breed FROM dogs WHERE gender = 'F';"
      3 
      4 
      5 

NameError: name 'f' is not defined

1 个答案:

答案 0 :(得分:0)

您的问题似乎缺少一些关键信息。错误NameError: name 'f' is not defined是Python错误,表示您所指的是所谓的f,尚未定义。

执行所提供的SQL并从Python运行以下脚本可以正常工作:

import sqlite3

connection = sqlite3.connect('pets.db')
cursor = connection.cursor()


def sql():
    return "SELECT name, breed FROM dogs WHERE gender = 'F';"


cursor.execute(sql()).fetchall()

出现此错误,您可能还会在发生此错误的地方收到行号和模块名称。您可能应该仔细看看确切的拼写与上面的区别。