1小時(shí)學(xué)會(huì) Python操作Mysql數(shù)據(jù)庫(kù)之pymysql模塊技術(shù):https://www.bilibili.com/video/BV1Dz4y1j7Jr
通過(guò)pymysql的Connection類(lèi)創(chuàng)建數(shù)據(jù)庫(kù)連接,用完一定要關(guān)閉連接。
from pymysql import Connection
# 創(chuàng)建數(shù)據(jù)庫(kù)連接
con = Connection(
host="localhost", # 主機(jī)名
port=3306, # 端口
user="root", # 賬戶(hù)
password="123456" # 密碼
)
print(type(con))
print(con.get_host_info())
print(con.get_server_info())
# 關(guān)閉連接
con.close()
運(yùn)行輸出:
<class 'pymysql.connections.Connection'>
socket localhost:3306
5.7.18-log
改進(jìn),可能會(huì)出現(xiàn)異常,我們加上 try except finally
from pymysql import Connection
con = None
try:
# 創(chuàng)建數(shù)據(jù)庫(kù)連接
con = Connection(
host="localhost", # 主機(jī)名
port=3306, # 端口
user="root", # 賬戶(hù)
password="123456" # 密碼
)
print(type(con))
print(con.get_host_info())
print(con.get_server_info())
except Exception as e:
print("異常:", e)
finally:
if con:
# 關(guān)閉連接
con.close()