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