1. 程式人生 > >python3使用pymysql連線Mysql 資料庫及 簡單的增刪改查操作

python3使用pymysql連線Mysql 資料庫及 簡單的增刪改查操作

示例表


1查詢操作


import pymysql  #匯入 pymysql  
  
#開啟資料庫連線  
db= pymysql.connect(host="localhost",user="root",  
    password="123456",db="test",port=3307)  
  
# 使用cursor()方法獲取操作遊標  
cur = db.cursor()  
  
#1.查詢操作  
# 編寫sql 查詢語句  user 對應我的表名  
sql = "select * from user"  
try:  
    cur.execute(sql)    #執行sql語句  
  
    results = cur.fetchall()    #獲取查詢的所有記錄  
    print("id","name","password")  
    #遍歷結果  
    for row in results :  
        id = row[0]  
        name = row[1]  
        password = row[2]  
        print(id,name,password)  
except Exception as e:  
    raise e  
finally:  
    db.close()  #關閉連線  

2插入操作


import pymysql  
#2.插入操作  
db= pymysql.connect(host="localhost",user="root",  
    password="123456",db="test",port=3307)  
  
# 使用cursor()方法獲取操作遊標  
cur = db.cursor()  
  
sql_insert ="""insert into user(id,username,password) values(4,'liu','1234')"""  
  
try:  
    cur.execute(sql_insert)  
    #提交  
    db.commit()  
except Exception as e:  
    #錯誤回滾  
    db.rollback()   
finally:  
    db.close()  

3更新操作


import pymysql  
#3.更新操作  
db= pymysql.connect(host="localhost",user="root",  
    password="123456",db="test",port=3307)  
  
# 使用cursor()方法獲取操作遊標  
cur = db.cursor()  
  
sql_update ="update user set username = '%s' where id = %d"  
  
try:  
    cur.execute(sql_update % ("xiongda",3))  #像sql語句傳遞引數  
    #提交  
    db.commit()  
except Exception as e:  
    #錯誤回滾  
    db.rollback()   
finally:  
    db.close()  

4刪除操作

import pymysql  
#4.刪除操作  
db= pymysql.connect(host="localhost",user="root",  
    password="123456",db="test",port=3307)  
  
# 使用cursor()方法獲取操作遊標  
cur = db.cursor()  
  
sql_delete ="delete from user where id = %d"  
  
try:  
    cur.execute(sql_delete % (3))  #像sql語句傳遞引數  
    #提交  
    db.commit()  
except Exception as e:  
    #錯誤回滾  
    db.rollback()   
finally:  
    db.close()