我在将包含姓名和电子邮件的 .txt 文件转换为 python SQLite 数据库时遇到问题。我的代码如下。当我运行 fetchall 命令时,会检索一个空列表(它运行时没有回溯)。
import sqlite3
conn=sqlite3.connect('email.db')
cur = conn.cursor()
cur.execute ('''DROP TABLE IF EXISTS Emaildb''')
cur.execute('''CREATE TABLE Emaildb (firstname TEXT, lastname TEXT, email TEXT)''')
fname = r'C:\Users\...emaillist.txt'
fh =open(fname)
for line in fh:
parts = line.split()
first_name = parts[0]
last_name = parts[1]
email = parts[-1]
cur.execute("INSERT INTO Emaildb(firstname,lastname,email) VALUES (?,?,?)",(first_name,last_name,email))
print(cur.fetchall())
conn.commit()
conn.close()
你可以这样尝试
import sqlite3
conn = sqlite3.connect('email.db')
cur = conn.cursor()
cur.execute('''DROP TABLE IF EXISTS Emaildb''')
cur.execute('''CREATE TABLE Emaildb (firstname TEXT, lastname TEXT, email TEXT)''')
fname = r'C:\Users\...emaillist.txt'
with open(fname, 'r') as fh:
for line in fh:
parts = line.split()
if len(parts) >= 3: # Ensure there are at least 3 parts (first name, last name, email)
first_name = parts[0]
last_name = parts[1]
email = parts[-1]
cur.execute("INSERT INTO Emaildb(firstname, lastname, email) VALUES (?, ?, ?)", (first_name, last_name, email))
else:
print(f"Issue with line: {line}")
# Fetching data to verify
cur.execute("SELECT * FROM Emaildb")
data = cur.fetchall()
print(data)
conn.commit()
conn.close()