SQLite in Python: 如何在Python中使用SQLite數據庫


SQLite3 可使用 sqlite3 模塊與 Python 進行集成。sqlite3 模塊是由 Gerhard Haring 編寫的。它提供了一個與 PEP 249 描述的 DB-API 2.0 規范兼容的 SQL 接口。您不需要單獨安裝該模塊,因為 Python 2.5.x 以上版本默認自帶了該模塊。

使用sqlite tutorial提供的 “chinook” sample database 數據庫chinook.db,下載地址:https://www.sqlitetutorial.net/sqlite-sample-database/

同時提供了數據庫的ER-Diagram實體關系圖, 可以使用數據庫提供的11張表進行一些練習。

 

import sqlite3

conn = sqlite3.connect('chinook.db')

cur = conn.cursor()

# treat the cursor object cur as an iterator
cur.execute('SELECT * from albums')

# call fetchone() method / or fetchall() method
print(cur.fetchone())

# iterating over each rows
for row in cur.execute('SELECT * from albums'):
    print(row)

cur.execute('SELECT * from customers')
print(cur.fetchone())

# add where clause 
ArtistId = ('272',)

# using ? is more secure than using %s
cur.execute('SELECT * from albums where ArtistId = ?',ArtistId)
print(cur.fetchall())

# using %s
ArtistId = ('272',)

# using ? is more secure than using %s
cur.execute('SELECT * from albums where ArtistId = %s' % ArtistId)
print(cur.fetchall())

cur.execute('SELECT * from artists')
print(cur.fetchall())

# insert value
cur.execute('INSERT OR REPLACE INTO artists values (276, "Jay Zhou")')
cur.execute('SELECT * from artists')
print(cur.fetchall())

# insert a list of records -- here we use executemany to insert another 3 singers
newArtists = [(278, 'Eason Chan'),
              (279, 'Yoga Lin'),
              (280, 'Jane Zhang'),]

# print(type(newArtists))
cur.executemany('INSERT OR IGNORE INTO artists values (? , ?)' , newArtists)
for row in cur.execute('SELECT * from artists'):
    print(row)

# using commit() to save those transactions / commiting those transations
conn.commit()
conn.close()

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM