1小時(shí)學(xué)會(huì) Python操作Mysql數(shù)據(jù)庫(kù)之pymysql模塊技術(shù):https://www.bilibili.com/video/BV1Dz4y1j7Jr
pymysql執(zhí)行DML語(yǔ)句
MySQL 數(shù)據(jù)庫(kù)模塊同樣可以使用游標(biāo)的execute()方法執(zhí)行DML(Data Manipulation Language, 數(shù)據(jù)操縱語(yǔ)言)的 insert、update、delete語(yǔ)句,對(duì)數(shù)據(jù)庫(kù)進(jìn)行插入、修改和刪除數(shù)據(jù)操作。
pymysql執(zhí)行select查詢(xún)操作
con = None
try:
# 創(chuàng)建數(shù)據(jù)庫(kù)連接
con = Connection(
host="localhost", # 主機(jī)名
port=3306, # 端口
user="root", # 賬戶(hù)
password="123456", # 密碼
database="db_python" # 指定操作的數(shù)據(jù)庫(kù)
)
# 獲取游標(biāo)對(duì)象
cursor = con.cursor()
# 使用游標(biāo)對(duì)象,執(zhí)行sql語(yǔ)句
cursor.execute("select * from t_student")
# 獲取查詢(xún)所有結(jié)果
result = cursor.fetchall()
print(type(result), result)
for row in result:
print(row)
except Exception as e:
print("異常:", e)
finally:
if con:
# 關(guān)閉連接
con.close()