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)建游標 cursor = conn.cursor() # 關(guān)閉游標 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é)果的所有(剩余)行,返回一個列表。請注意,游標的 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.
基礎(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練習之操作SQLite數(shù)據(jù)庫
- SQLite5-使用Python來讀寫數(shù)據(jù)庫
- Pandas使用SQLite3實戰(zhàn)
相關(guān)文章
Python設(shè)置Word全局樣式和文本樣式的示例代碼
這篇文章主要介紹了如何利用Python對Word內(nèi)容進行各種樣式的設(shè)置,讓其能夠看起來更加的美觀。文中的示例代碼講解詳細,需要的可以參考一下2022-05-05Python3之不使用第三方變量,實現(xiàn)交換兩個變量的值
今天小編就為大家分享一篇Python3之不使用第三方變量,實現(xiàn)交換兩個變量的值,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-06-06Python基礎(chǔ)必備之語法結(jié)構(gòu)詳解
Python語法定義了用于在 Python 編程中創(chuàng)建句子的所有規(guī)則集。如果想更深入地研究 Python 詞法結(jié)構(gòu),需要了解構(gòu)成語句的句法元素,即構(gòu)成 Python 程序的基本單元,涵蓋控制結(jié)構(gòu),在不同代碼組之間引導程序流的構(gòu)造,快跟隨小編一起學習一下吧2022-04-04Python中函數(shù)的參數(shù)傳遞與可變長參數(shù)介紹
這篇文章主要介紹了Python中函數(shù)的參數(shù)傳遞與可變長參數(shù)介紹,本文分別給出多個代碼實例來講解多種多樣的函數(shù)參數(shù),需要的朋友可以參考下2015-06-06