设为首页 加入收藏

TOP

SQLite in Python: 如何在Python中使用SQLite数据库
2019-09-25 18:11:20 】 浏览:37
Tags:SQLite Python: 何在 Python 使用 数据库

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

 

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇Python实现十大经典排序算法(史.. 下一篇牛客网 ---- 学数学

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目