日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網(wǎng)站首頁 編程語言 正文

python處理SQLite數(shù)據(jù)庫的方法_python

作者:Crayon鑫 ? 更新時間: 2022-04-25 編程語言

前言:

數(shù)據(jù)庫非常重要,程序的數(shù)據(jù)增刪改查需要數(shù)據(jù)庫支持。python處理數(shù)據(jù)庫非常簡單。而且不同類型的數(shù)據(jù)庫處理邏輯方式大同小異。本文以sqlite數(shù)據(jù)庫為例,介紹一下python操作數(shù)據(jù)庫的方法。

python sqlite3 官方文檔

一、安裝

pip3 install pysqlite3

三、數(shù)據(jù)庫連接、關閉等

import sqlite3
# 連接數(shù)據(jù)庫(如果不存在則創(chuàng)建)
conn = sqlite3.connect('test.db')
print("Opened database successfully")
?
# 創(chuàng)建游標
cursor = conn.cursor()

# 關閉游標
cursor.close()
# 提交事物
conn.commit()
# 關閉連接
conn.close()

四、表操作

1、創(chuàng)建數(shù)據(jù)表

import sqlite3

conn = sqlite3.connect('test.db')
print ("數(shù)據(jù)庫打開成功")
c = conn.cursor()
c.execute('''CREATE TABLE COMPANY
? ? ? ?(ID INT PRIMARY KEY ? ? NOT NULL,
? ? ? ?NAME ? ? ? ? ? TEXT ? ?NOT NULL,
? ? ? ?AGE ? ? ? ? ? ?INT ? ? NOT NULL,
? ? ? ?ADDRESS ? ? ? ?CHAR(50),
? ? ? ?SALARY ? ? ? ? REAL);''')
print ("數(shù)據(jù)表創(chuàng)建成功")
conn.commit()
conn.close()

2、顯示數(shù)據(jù)表數(shù)目

sql="select name from sqlite_master where type='table' order by name"
tables=cursor.execute(sql).fetchall()
print(len(tables))

3、刪除數(shù)據(jù)表

sql="DROP TABLE database_name.table_name"
cursor.execute(sql)

五、Cusor的一些方法

fetchone()

獲取查詢結果集的下一行

fetchmany(size=cursor.arraysize)

獲取查詢結果的下一組行,返回一個列表。

fetchall()

取查詢結果的所有(剩余)行,返回一個列表。請注意,游標的 arraysize 屬性會影響此操作的性能。當沒有行可用時返回一個空列表。

注:fetchall()用來統(tǒng)計表記錄時,在開頭用一次,再用則查詢?yōu)榭?/p>

.description顯示字段信息,返回列表。

六、SQL操作

1、查

...
# 創(chuàng)建游標
cursor = conn.cursor()
?
# 查詢數(shù)據(jù)
sql = "select * from Student"
values = cursor.execute(sql)
for i in values:
? ? print(i)
?
# 查詢數(shù)據(jù) 2
sql = "select * from Student where id=?"
values = cursor.execute(sql, (1,))
for i in values:
? ? print('id:', i[0])
? ? print('name:', i[1])
? ? print('age:', i[2])
?
# 提交事物
conn.commit()
...

2、增

...
# 創(chuàng)建游標
cursor = conn.cursor()
?
# 插入數(shù)據(jù)
sql = "INSERT INTO Student(Name, Age) VALUES(\'love\', 22)"
cursor.execute(sql)
?
# 插入數(shù)據(jù) 2
data = ('love2', 2221) # or ['love2', 2221]
sql = "INSERT INTO Student(Name, Age) VALUES(?, ?)"
cursor.execute(sql, data)
?
# 提交事物
conn.commit()
...

3、刪

sql語句換一下即可,看下一節(jié)的SQL語句。

4、改

sql語句換一下即可,看下一節(jié)的SQL語句。

七、SQL常用語句

# 增 ? 兩種方法
sql1="INSERT INTO table_name VALUES (value1,value2,value3,...);"
sql2='''INSERT INTO table_name?
?? ?(column1,column2,column3,...)?
?? ?VALUES (value1,value2,value3,...);'''
# 刪
sql="DELETE FROM table_name WHERE [condition];"
# 改
sql="UPDATE table_name SET column1 = value1, column2 = value2...., columnN = valueN WHERE [condition];"
# 查
sql="SELECT * FROM table_name;"

# 重命名
sql="ALTER TABLE 老表名 RENAME TO 新表名;"
# 添加字段
sql="ALTER TABLE 表名 ADD COLUMN 新列 TEXT;"

# 查看所有字段名
sql="PRAGMA table_info([表名])"

八、row_factory 高級操作

這是對row_factory的官方解釋(官方解釋直接忽略就好,看我下面的解釋):A Row instance serves as a highly optimized row_factory for Connection objects. It tries to mimic a tuple in most of its features.
It supports mapping access by column name and index, iteration, representation, equality testing and len().
If two Row objects have exactly the same columns and their members are equal, they compare equal.

基礎Cursor對象只能通過數(shù)字索引來獲取值,但是我想通過列名來獲取值是做不到的。雖然可以使用Cursor.description來獲取字段名稱,但是自己做映射寫代碼很麻煩。
本著簡約代碼(懶)的原則,python推出了Cursor.Row對象。其實就是列名和值做了個映射,可以通過字符索引來獲取值。很方便。
升級過程也簡單,就加一句話:conn.row_factory = sqlite3.Row

看例子:

1、使用

import sqlite3?
conn=connectSqlite("myDB.db")
conn.row_factory = sqlite3.Row # 這句一定要加
cursor=conn.cursor()
rows=cursor.execute("SELECT * from myTable ")

row=rows.fetchone()
row.key() # 返回所有字段名,
print(row[0]) # 輸出第一個字段
print(row["field1"]) # 輸出字段名為field1的值

2、循環(huán)輸出所有值

# ...上接上面的第一塊內(nèi)容
s=0
for row in rows:# 迭代就不用fetchone()了
?? ?s+=1
?? ?print("打印第{}個數(shù)據(jù)".format(s))
?? ?for r in row:
?? ??? ?print(r)

九、實例

1、從sqlite數(shù)據(jù)庫中返回json格式數(shù)據(jù)

'''
description: 根據(jù)輸入條件,從sqlite數(shù)據(jù)庫中返回JSON數(shù)據(jù)?
param {*} db_name:str 數(shù)據(jù)庫名稱
param {*} fields:list 篩選的字段
param {*} table_name:str 要查詢的表名
param {*} condition:str 查詢的條件,注意條件的值是字符串的話需要轉(zhuǎn)義
return {*} json
author: https://blog.csdn.net/Crayonxin2000
'''
def returnJsonFromSqlite(db_name,fields,table_name,condition):
? ? data = {}
? ? rows = [] ?# 數(shù)據(jù)
? ? conn = connectSqlite(db_name)
? ? conn.row_factory = sqlite3.Row
? ? cursor = conn.cursor()
? ? fields_str = ",".join(fields) ?# 列表轉(zhuǎn)字段,fields為所有的字段
? ? if condition=="" or condition==None:
? ? ? ? sql="SELECT {} from {} ".format(fields_str,table_name)
? ? else:
? ? ? ? sql="SELECT {} from {} WHERE {}".format(fields_str,table_name,condition)
? ? print(sql)
? ? result=cursor.execute(sql)
? ? for item in result:
? ? ? ? row = []
? ? ? ? for field in fields:
? ? ? ? ? ? row.append(item[field])
? ? ? ? rows.append(row)
? ? data["header"] = fields
? ? data["rows"] = rows
? ? # 關閉數(shù)據(jù)庫
? ? cursor.close()
? ? conn.close()
? ? return jsonify(data)?

注:data是字典,我用flask的jsonify工具JSON化了,你可以使用其他工具。

原文鏈接:https://blog.csdn.net/Crayonxin2000/article/details/122506157

欄目分類
最近更新