網(wǎng)站首頁 編程語言 正文
前言:
數(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
相關推薦
- 2022-03-07 C語言中的rand()和rand_r()詳解_C 語言
- 2022-07-16 feign調(diào)用傳遞請求頭
- 2023-01-17 Keras中Sequential模型和Functional模型的區(qū)別及說明_python
- 2022-12-01 Docker系列學習之Swarm?mode管理節(jié)點常用命令詳解_docker
- 2022-03-30 python生成密碼字典詳解_python
- 2022-06-07 FreeRTOS實時操作系統(tǒng)臨界段保護場合示例_操作系統(tǒng)
- 2023-07-04 如何替換spring boot中spring框架的版本
- 2022-10-29 python使用正則表達式匹配反斜杠\遇到的問題_python
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細win安裝深度學習環(huán)境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結構-簡單動態(tài)字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支