python数据库操作实例
生活随笔
收集整理的這篇文章主要介紹了
python数据库操作实例
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
本篇文章主要講解python3.9.6下數(shù)據(jù)庫的鏈接和查詢數(shù)據(jù)的方法
前置環(huán)境需要安裝mysql和json兩個模塊,引入方式為import 模塊名,不懂的朋友可以先看《python小白操作入門教程》
查詢多條數(shù)據(jù)實例代碼:
代碼實例: import pymysql,json print("默認(rèn)數(shù)據(jù)庫地址為localhost,數(shù)據(jù)庫名為performance_schema。") host_user = input("輸入你的數(shù)據(jù)庫用戶:") host_pwd = input("輸入你的數(shù)據(jù)庫密碼:") print("請確保performance_schema數(shù)據(jù)庫可以訪問并已創(chuàng)建,否則程序會報錯") db = pymysql.connect(host='127.0.0.1', user=host_user, password = host_pwd, database="performance_schema", charset='utf8' ) cursor = db.cursor() sql = 'show tables' cursor.execute(sql) //輸出多條數(shù)據(jù) for tabs in cursor:print(tabs) db.close()查詢單條數(shù)據(jù)實例代碼:
import pymysql,json print("默認(rèn)數(shù)據(jù)庫地址為localhost,數(shù)據(jù)庫名為performance_schema。") host_user = input("輸入你的數(shù)據(jù)庫用戶:") host_pwd = input("輸入你的數(shù)據(jù)庫密碼:") print("請確保performance_schema數(shù)據(jù)庫可以訪問并已創(chuàng)建,否則程序會報錯") db = pymysql.connect(host='127.0.0.1', user=host_user, password = host_pwd, database="performance_schema", charset='utf8' ) cursor = db.cursor() sql = '你的sql語句' cursor.execute(sql) //單條數(shù)據(jù) data = cursor.fetchone() db.close() print(json.dumps(data))插入和刪除更新數(shù)據(jù)的方法
cursor.execute('你的sql語句,直接使用sql進(jìn)行更新和添加數(shù)據(jù)');總結(jié)
以上是生活随笔為你收集整理的python数据库操作实例的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java web 邮件_JavaWeb
- 下一篇: python 第一行 报错_初学Pyth