python3 mysql增刪改查
阿新 • • 發佈:2018-12-14
示例表 test
插入操作
import pymysql #匯入pymysql db=pymysql.connect(host="localhost", user="root", password="root", db="test", port=3306 ) #建立資料庫物件 cur = db.cursor() sql = "INSERT INTO `test` (`id`, `name`, `password`) VALUES ('3', 'test1', 'test1')" try: cur.execute(sql) #執行sql db.commit() #提交 except Exception as e: db.rollback() #異常回滾 finally: db.close()
查詢操作
import pymysql #匯入pymysql db=pymysql.connect(host="localhost", user="root", password="root", db="test", port=3306 ) #建立資料庫物件 cur = db.cursor() #獲取遊標 sql = "select * from test" try: cur.execute(sql) res = cur.fetchall() #查詢多條資料,使用迴圈進行輸出 #res = cur.fetchone() #查詢一條 直接輸出 print("id","name","password") #print(res) for row in res: id = row[0] name = row[1] password = row[2] print(id,name,password) except Exception as e: raise e finally: db.close()
更新操作
import pymysql #匯入pymysql db=pymysql.connect(host="localhost", user="root", password="root", db="test", port=3306 ) #建立資料庫物件 cur = db.cursor() sql = "UPDATE test set name = '%s',password = '%s' where id = %d" try: cur.execute(sql% ("ddd","ddd",2)) db.commit() except Exception as e: db.rollback() finally: db.close()
刪除操作
import pymysql #匯入pymysql
db=pymysql.connect(host="localhost",
user="root",
password="root",
db="test",
port=3306
) #建立資料庫物件
cur = db.cursor()
sql = "DELETE from test where id = %d"
try:
cur.execute(sql% (2))
db.commit()
except Exception as e:
db.rollback()
finally:
db.close()