[英]sqlite3.OperationalError: no such column: Python and Sqllite3
我的代碼:
從 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/email grabber.py”,第 79 行,在 email_address_grab(["testemail123@gmail.com"])
文件“c:/Users/USER/Desktop/email grabber.py”,第 58 行,在 email_address_grab crsr.execute(cmd)
sqlite3.OperationalError:沒有這樣的列:'testemail123','gmail.com'
您的問題是因為這是您的最終命令字符串:
"""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))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.