sqlite3 數(shù)據(jù)庫(kù)是 Python 自帶的數(shù)據(jù)庫(kù),不需要額外安裝模塊翠拣,而且操作簡(jiǎn)單版仔。
1.創(chuàng)建數(shù)據(jù)庫(kù),我們直接在桌面右鍵單擊選擇《新建》,選擇《文本文檔》蛮粮,然后把這個(gè)文件重名為a.db在復(fù)制到d盤(pán)根目錄(放其他盤(pán)也可以益缎,但路徑中不能有中文), 這樣我們的數(shù)據(jù)庫(kù)就創(chuàng)建好了然想,如下圖
2.連接數(shù)據(jù)庫(kù)
#連接數(shù)據(jù)庫(kù)
db=sqlite3.connect("d:\\a.db")
3.創(chuàng)建表數(shù)據(jù)
#創(chuàng)建表
db.execute("""CREATE TABLE user (id integer primary key AUTOINCREMENT,title text NULL,)""")
id integer primary key AUTOINCREMENT
這句sql語(yǔ)句代表id為主鍵并進(jìn)行自增
title text NULL
這句sql語(yǔ)句代表創(chuàng)建text字段莺奔,數(shù)據(jù)可以是空的
4.查詢(xún)數(shù)據(jù)
#查詢(xún)數(shù)據(jù)
def getAll(path):
db=sqlite3.connect(path)
cu=db.cursor()
cu.execute("SELECT * FROM user")
res=cu.fetchall()
cu.close()
db.close()
return res
5.添加數(shù)據(jù)
#添加
def add(title,path):
db=sqlite3.connect(path)
cu=db.cursor()
cu.execute("insert into user values(NULL,'"+title+"')")
db.commit()
cu.close()
6.刪除數(shù)據(jù)
#刪除
def delate(name,path):
db=sqlite3.connect(path)
cu=db.cursor()
cu.execute("delete from user where id="+str(name))
db.commit()
cu.close()
7.分頁(yè)查詢(xún)
#分頁(yè)
def limit(p,path):
db=sqlite3.connect(path)
cu=db.cursor()
cu.execute("SELECT * FROM user limit "+p+",10")
res=cu.fetchall()
cu.close()
db.close()
return res
一些簡(jiǎn)單常用的sql語(yǔ)句
#模糊查詢(xún)
select * from user where title like '%小明%'
#統(tǒng)計(jì)數(shù)據(jù)總數(shù)
select count(id) from user
#根據(jù)id查詢(xún)
select * from user where id = 1
#根據(jù)id刪除記錄
delete from user where id = 1
#插入數(shù)據(jù)
insert into user values(NULL,‘小明’)
#查詢(xún)表所有數(shù)據(jù)
select * from user
#獲取指定位置后面的10條數(shù)據(jù) (分頁(yè))
select * from user limit 1,10