python處理SQLite數(shù)據(jù)庫的方法
前言:
數(shù)據(jù)庫非常重要,程序的數(shù)據(jù)增刪改查需要數(shù)據(jù)庫支持。python處理數(shù)據(jù)庫非常簡單。而且不同類型的數(shù)據(jù)庫處理邏輯方式大同小異。本文以sqlite數(shù)據(jù)庫為例,介紹一下python操作數(shù)據(jù)庫的方法。
一、安裝
pip3 install pysqlite3
三、數(shù)據(jù)庫連接、關(guān)閉等
import sqlite3
# 連接數(shù)據(jù)庫(如果不存在則創(chuàng)建)
conn = sqlite3.connect('test.db')
print("Opened database successfully")
?
# 創(chuàng)建游標(biāo)
cursor = conn.cursor()
# 關(guān)閉游標(biāo)
cursor.close()
# 提交事物
conn.commit()
# 關(guān)閉連接
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()
獲取查詢結(jié)果集的下一行
fetchmany(size=cursor.arraysize)
獲取查詢結(jié)果的下一組行,返回一個列表。
fetchall()
取查詢結(jié)果的所有(剩余)行,返回一個列表。請注意,游標(biāo)的 arraysize 屬性會影響此操作的性能。當(dāng)沒有行可用時返回一個空列表。
注:fetchall()用來統(tǒng)計表記錄時,在開頭用一次,再用則查詢?yōu)榭?/p>
.description顯示字段信息,返回列表。
六、SQL操作
1、查
...
# 創(chuàng)建游標(biāo)
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)建游標(biāo)
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.
基礎(chǔ)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
? ? # 關(guān)閉數(shù)據(jù)庫
? ? cursor.close()
? ? conn.close()
? ? return jsonify(data)?注:data是字典,我用flask的jsonify工具JSON化了,你可以使用其他工具。
到此這篇關(guān)于python處理SQLite數(shù)據(jù)庫的方法的文章就介紹到這了,更多相關(guān)python處理SQLite數(shù)據(jù)庫內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- Python中如何使用sqlite3操作SQLite數(shù)據(jù)庫詳解
- 使用Python連接SQLite數(shù)據(jù)庫的操作步驟
- 通過python封裝SQLite3的示例代碼
- Python數(shù)據(jù)庫編程之SQLite和MySQL的實踐指南
- Python的sqlite3模塊中常用函數(shù)
- Python中SQLite數(shù)據(jù)庫的使用
- Python數(shù)據(jù)庫sqlite3圖文實例詳解
- Python使用sqlite3第三方庫讀寫SQLite數(shù)據(jù)庫的方法步驟
- Python練習(xí)之操作SQLite數(shù)據(jù)庫
- SQLite5-使用Python來讀寫數(shù)據(jù)庫
- Pandas使用SQLite3實戰(zhàn)
相關(guān)文章
python實現(xiàn)將json多行數(shù)據(jù)傳入到mysql中使用
這篇文章主要介紹了python實現(xiàn)將json多行數(shù)據(jù)傳入到mysql中使用,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-12-12
解決pycharm不能自動補全第三方庫的函數(shù)和屬性問題
這篇文章主要介紹了解決pycharm不能自動補全第三方庫的函數(shù)和屬性問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-03-03
openCV-Python筆記之解讀圖像的讀取、顯示和保存問題
這篇文章主要介紹了openCV-Python筆記之解讀圖像的讀取、顯示和保存問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-12-12
Python實現(xiàn)數(shù)據(jù)可視化大屏布局的示例詳解
數(shù)據(jù)可視化大屏展示需求無疑是對數(shù)據(jù)分析結(jié)果最好的詮釋,能夠使得別人能夠輕松的就理解我們的數(shù)據(jù)意圖。本文將通過pyecharts模塊來實現(xiàn),感興趣的可以了解一下2022-11-11
PyCharm MySQL可視化Database配置過程圖解
這篇文章主要介紹了PyCharm MySQL可視化Database配置過程圖解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-06-06
python非標(biāo)準(zhǔn)時間的轉(zhuǎn)換
本文主要介紹了python非標(biāo)準(zhǔn)時間的轉(zhuǎn)換,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-07-07

