使用Sqlite3使用循环将数据插入数据库

时间:2022-06-01 21:28:38

I'm just getting started with databases and could use help inserting information into a database using a loop.

我刚刚开始使用数据库,可以使用循环将帮助信息插入到数据库中。

I made a simple database table with three headings: ISBN, Author, Price.

我制作了一个简单的数据库表,其中包含三个标题:ISBN,作者,价格。

I would like to use lists containing the ISBNs, Authors, and Prices and insert each ISBN, Author, and Price to the database table using one for loop.

我想使用包含ISBN,作者和价格的列表,并使用一个for循环将每个ISBN,作者和价格插入数据库表。

Here is my code:

这是我的代码:

ISBN1=ISBNs[0]
Author1=Authors[0]
Price1=Prices[0]


db=sqlite3.connect('My_Book_Inventory.sqlite')
cursor=db.cursor()
cursor.execute('''Insert INTO ISBNS(ISBN,Author,Price) VALUES(?,?,?)''',(ISBN1,Author1,Price1))
db.commit()  

Could someone help me get from inserting each ISBN manually by calling the values in the lists ISBN1, ISBN2, ISBN3 etc. into actually doing this all with a loop?

有人可以通过调用列表ISBN1,ISBN2,ISBN3等中的值手动插入每个ISBN来帮助我实际上通过循环实现这一切吗?

1 个解决方案

#1


0  

Lets say you have n records that you want to insert them. Assuming ISBNs, Authors and Prices are arrays of size n, you can do this:

假设您有n条记录要插入它们。假设ISBN,作者和价格是大小为n的数组,您可以这样做:

for i in range(0, n):
    ISBN = ISBNs[i]
    Author = Authors[i]
    Price = Prices[i]

    db=sqlite3.connect('My_Book_Inventory.sqlite')
    cursor=db.cursor()
    cursor.execute('''Insert INTO ISBNS(ISBN,Author,Price) VALUES(?,?,?)''',(ISBN,Author,Price))
    db.commit()

#1


0  

Lets say you have n records that you want to insert them. Assuming ISBNs, Authors and Prices are arrays of size n, you can do this:

假设您有n条记录要插入它们。假设ISBN,作者和价格是大小为n的数组,您可以这样做:

for i in range(0, n):
    ISBN = ISBNs[i]
    Author = Authors[i]
    Price = Prices[i]

    db=sqlite3.connect('My_Book_Inventory.sqlite')
    cursor=db.cursor()
    cursor.execute('''Insert INTO ISBNS(ISBN,Author,Price) VALUES(?,?,?)''',(ISBN,Author,Price))
    db.commit()