sqlite3.OperationalError:无此类列:Python和Sqllite3

时间:2020-07-27 19:53:34

标签: python sql sqlite

我的代码:

从Python 3.8起

def email_address_grab(email_list):

""" This function takes in a list of emails and puts them into a sql database"""


#import module
import sqlite3 as sql


#Setup sql
#create connection for sql
connection = sql.connect("emailList.db")

#create cursor
crsr = connection.cursor()

 #create sql table
cmd = """CREATE TABLE emails (
email_handle TEXT,
email_domain VARCHAR(20));"""
crsr.execute(cmd)


#iterate through email list
index = 0
for email in email_list:
    #split email with a delimiter of "@"
    email_list[index] = email.split('@')
    index += 1

#while loop to put all data into table
ct = 0
while ct <= (len(email_list) - 1):
    for i in range(0, len(email_list)):
        for j in range(0, len(email_list)):
            email_address_1 = email_list[i]
            email_address_2 = email_list[j]
            cmd = f"""INSERT INTO emails (email_handle, email_domain) VALUES ({email_address_1}, {email_address_2});"""
            crsr.execute(cmd)
    ct += 1


#get the contents of the table
crsr.execute("SELECT * FROM emails;")

#store contents in a variable
email_address_list = crsr.fetchall()

#save changes to sql table
connection.commit()

#close connection
connection.close()


#return print statement for data
return print(email_address_list)

错误:

回溯(最近通话最近一次):

文件“ c:/ Users / USER / Desktop /电子邮件grabber.py”,第79行,在 email_address_grab([“ testemail123@gmail.com”])

文件“ c:/Users/USER/Desktop/emailgraber.py”,第58行,在email_address_grab中 crsr.execute(cmd)

sqlite3.OperationalError:没有这样的列:'testemail123','gmail.com'

1 个答案:

答案 0 :(得分:0)

您的问题是因为这是您的最终命令字符串:

"""INSERT INTO emails (email_handle, email_domain) VALUES (testemail123, gmail.com);"""

有效字符串是:

"""INSERT INTO emails (email_handle, email_domain) VALUES ("testemail123", "gmail.com");"""

所以您应该使用类似这样的东西:

cmd = f"""INSERT INTO emails (email_handle, email_domain) VALUES ('{email_address_1}', '{email_address_2}');"""

尽管使用sqlite3,您应该通过execute调用传递参数。这有助于防止 sql注入攻击,因为使用格式化字符串的方式可能会导致灾难性攻击。

您应该像这样将参数传递给sqlite3实例:

cmd = """INSERT INTO emails (email_handle, email_domain) VALUES (?, ?);"""
crsr.execute(cmd, (email_address_1, email_address_2))