将数组插入数据库 SQL Python SqLite3 而不使用“access_database_with_result”查询

问题描述 投票:0回答:1

我正在尝试将二维数组插入到数据库中,其中二维数组可能会有所不同。我正在使用 SQlite3 和“access_database_with_result”查询。

我已经尝试了很多尝试来使其正常工作,并且做了很多研究,但还没有找到解决方案。 我得到的最接近的是。

access_database_with_result(database, "INSERT INTO Assignments (AssignmentID, StudentID, AssessmentID, Deadline, Submitted, Mark, Marked) VALUES (?, ?, ?, ?, ?, ?, ?)", (b[I][0],b[I][1],b[I][2],b[I][3],b[I][4],b[I][5],b[I][6]));
结尾为

     17     cursor = connect.cursor()
---> 18     rows = cursor.execute(query, parameters).fetchall()
     19     connect.commit()
     20     connect.close()

OperationalError: database is locked

(注意,这不是重复的,因为其他类似问题都没有对我有用的答案。我真的需要解决这个问题,否则我将面临课程不及格的风险。)

python sql sqlite
1个回答
0
投票

您遇到的错误与您的 INSERT 语句无关。每次尝试执行事务时都会抛出该错误,因为您的数据库已锁定。这可能是因为您尝试了禁止的事情(参见post

如果你想实现插入 - 我认为这是实际问题 - 你可以尝试这个:

import sqlite3
con = sqlite3.connect("mydb.db")
cur = con.cursor()
# Create the table if it does not exist
cur.execute("CREATE TABLE Assignments(AssignmentID, StudentID, AssessmentID, Deadline, Submitted, Mark, Marked)")
# Construct a list of tuples from your 2D array - here you have to cast your array into a list of tuples
b = [(0,1,2,3,4,5,6) for __ in range(10)]
# Manipulate your query with the 2D array
query = "INSERT INTO Assignments (AssignmentID, StudentID, AssessmentID, Deadline, Submitted, Mark, Marked) VALUES "
for i in b:
    query += str(i) + ","
# Insert the data, (query[:-1]) the last charachter is a ',' which causes a syntax error
cur.execute(query[:-1])
# get the inserted rows
res = cur.execute(f"SELECT * FROM Assignments LIMIT {len(b)}").fetchall()
print(res)
© www.soinside.com 2019 - 2024. All rights reserved.