几天来,我一直在尝试找出如何插入SQL表中。我没有尝试过任何方法,只是花了几个小时来修复所有错误,才发现我回到了插入语句不插入任何内容的开始。我只剩下几个小时了,在此问题解决之前,我无法用我的代码做任何其他事情,谢谢。
我根本不明白哪里出了问题,也不再有任何错误。它只是打印出没有任何内容的表。我希望它打印出我的输入(它们在完整的代码中定义,我已经检查了它们的工作原理并打印出来)
def insert_user():
import sqlite3
score = "0"
db = sqlite3.connect("Database.db")
cursor = db.cursor()
sql = "INSERT INTO users (username,firstname, surname, age, password , score) VALUES (?,?,?,?,?,?)"
db.execute(sql,(usernamei, first_name ,last_name , age, passwordi ,score))
db.commit()
result = cursor.fetchall()
print()
print("{0:<20} {1:<20} {2:<20} {3:<20} {4:<20} {5:<20}".format("userID","username","firstname","surname","age","password","score"))
print("====================================================================================================")
for each in result:
print("{0:<20} {1:<20} {2:<20} {3:<20} {4:<20} {5:<20}".format(each[1],each[2],each[3],each[4],each[5],each[6]))
insert_user()
答案 0 :(得分:1)
当您插入,删除,更新光标时,将不使用它们。要从使用(执行) SELECT SQL的表中获取数据,光标将包含结果集。
因此,您需要执行插入操作,然后执行选择,例如使用“ SELECT * FROM users”,然后使用result = cursor.fetchall()
。
而不是针对游标执行连接。
类似的东西(用于测试表的创建和删除以及使用硬编码的值(显然会相应地进行调整)):-
def insert_user():
import sqlite3
score = "0"
db = sqlite3.connect("Database.db")
sql = "DROP TABLE IF EXISTS users"
db.execute(sql)
sql = "CREATE TABLE IF NOT EXISTS users (userID INTEGER PRIMARY KEY, username TEXT UNIQUE, firstname TEXT, surname TEXT, age INTEGER, password TEXT, score INTEGER)"
db.execute(sql)
result = db.cursor()
sql = "INSERT INTO users (username,firstname, surname, age, password , score) VALUES (?,?,?,?,?,?)"
db.execute(sql,("testusername", "testfirstname","testsurname" , 10, "password" ,score))
db.commit()
result.execute("SELECT * FROM users")
print("{0:<20} {1:<20} {2:<20} {3:<20} {4:<20} {5:<20} {6:<20}".format("userID","username","firstname","surname","age","password","score"))
print("====================================================================================================")
for each in result:
print("{0:<20} {1:<20} {2:<20} {3:<20} {4:<20} {5:<20} {6:20}".format(each[0],each[1],each[2],each[3],each[4],each[5],each[6]))
insert_user()
结果:-
E:\PYCharmPythonProjects\venv\Scripts\python.exe E:/PYCharmPythonProjects/Test001.py
userID username firstname surname age password score
====================================================================================================
1 testusername testfirstname testsurname 10 password 0
Process finished with exit code 0