一、安裝方法:mysql
pip install records mysqlclientsql
二、鏈接數據庫:數據庫
1 import records 2 # root:數據庫用戶名 3 # root:數據密碼 4 # localhost:數據庫地址 5 # 3306:數據庫端口號 6 # mytest:數據庫名稱 7 db = records.Database('mysql://root:root@localhost:3306/mytest?charset=utf8')
三、簡單的查詢:json
# 查詢數據 rows = db.query("select * from user") for r in rows: print(r.id, r.mobile, r.passwd)
四、獲取查詢結果的方法介紹:ui
查詢到數據之後,能夠經過all()方法獲取全部的記錄,支持3種類型。spa
◆ 默認是本身封裝的RecordCollection對象3d
◆ 也能夠經過as_dict=True參數轉成字典形式excel
◆ 能夠經過as_ordereddict=True轉成排序字典形式code
# 獲取第一條數據 print(rows.first()) # 以字典形式獲取第一個 print(rows.first(as_dict=True)) # 查詢惟一的一個 print(rows.one()) # 獲取全部數據 print("all方法獲取全部數據:", rows.all()) # 轉爲json # print(rows.as_dict()) print(rows.all(as_dict=True)) # 排序字典 print(rows.first(as_ordereddict=True)) # 導出爲具體格式,支持: csv、yaml、json、xls、df(DataFrame) print(rows.export("yaml")) # 轉爲表格形式 print(rows.dataset) # 數據導出到excel文件 with open("user.xlsx","wb") as f: f.write(rows.export("xlsx"))
五、插入單條數據:對象
# 支持variable定義變量,經過參數傳入完成動態傳值,在須要動態加載數據的時候很是有用: user = {"mobile": "13066669999", "passwd": "666666"} sql = 'insert into user(mobile,passwd) values (:mobile,:passwd)' res = db.query(sql, **user) # 獲取返回結果 # print(res.pending) if res.pending: print("插入成功") else: print("插入失敗")
六、插入多條數據
users = [ {"mobile": "13066660000", "passwd": "666666"}, {"mobile": "13066660001", "passwd": "666666"}, {"mobile": "13066660002", "passwd": "666666"} ] sql = 'insert into user(mobile,passwd) values (:mobile,:passwd)' res = db.bulk_query(sql, users)
參考資料:
https://mp.weixin.qq.com/s?__biz=MzUxMTA3NzgzMQ==&mid=2247491479&idx=1&sn=072c4412dd62ba928e4d1724ad636f9c&chksm=f978633fce0fea29163f527657febee6e9d4e0bd57387df9878adf8d81bd64915d9afe832d64&mpshare=1&scene=1&srcid=&sharer_sharetime=1566521957255&sharer_shareid=07a84e301bcab5607399b81d4cf8c58c&key=7e5df62132e2da6f6ca89e1f9d018cb48763871a895c4685206f95637a38610399e6a10a9db05e9eaa32d52289b4baf3e078f38216e660aa76065a913c6f0f7ca53da6b9c495e9cfb8b472e23913d5af&ascene=1&uin=MjI4MzU0MzI0MQ%3D%3D&devicetype=Windows+10&version=62060844&lang=zh_CN&pass_ticket=hOFgLRgrATK184vvb5U7D27bmc%2FJ6luldzn0Fh9w3qo797LhhxGiOflgYubWpW%2BT