1. 程式人生 > >python3 pymysql操作資料庫

python3 pymysql操作資料庫

#pymysql操作資料庫
import pymysql
# 開啟資料庫連線
db = pymysql.connect(host="192.168.254.24", user="root",
                     password="root", db="mysql", port=3306)

# 使用cursor()方法獲取操作遊標
cur = db.cursor()

# 1.查詢操作
# 編寫sql 查詢語句  user 對應我的表名
sql = "select host,user,password from user"
try:
    cur.execute(sql)  # 執行sql語句
    results 
= cur.fetchall() # 獲取查詢的所有記錄 for i in results:#遍歷結果 print(i) except Exception as e: raise e finally: db.close() # 關閉連線