无论我尝试多少种不同的类型,插入语句都行不通。 sqlite3 pyscripter

Insert statement never works, no matter how many different types I try. Sqlite3 pyscripter

几天来我一直在努力研究如何插入 SQL table。我尝试的任何方法都不起作用,我只是花了几个小时修复所有错误,发现我回到了插入语句不插入任何内容的起点。我只剩下几个小时了,在解决此问题之前我无法对我的代码做任何其他事情,谢谢。

我完全不明白哪里出了问题,现在也没有任何错误了。它只是打印出 table 而没有任何内容。我希望它打印出我的输入(它们在完整代码中定义,我已经检查过它们是否有效并打印)

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()

当您插入、删除、更新时,不使用游标。要从 table 中获取数据,您可以使用(执行)SELECT SQL,然后游标将包含结果集。

因此您需要执行插入,然后执行 SELECT 例如使用 "SELECT * FROM users" 然后使用 result = cursor.fetchall().

不是针对连接执行,而是针对游标执行。

类似的东西(为了测试 table 被删除和创建并使用硬编码值(显然相应地调整)):-

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