Python知識分享網 - 專業(yè)的Python學習網站 學Python,上Python222
pymysql創(chuàng)建數據庫連接
發(fā)布于:2023-09-19 10:36:01

1小時學會 Python操作Mysql數據庫之pymysql模塊技術https://www.bilibili.com/video/BV1Dz4y1j7Jr

 

 

 

通過pymysql的Connection類創(chuàng)建數據庫連接,用完一定要關閉連接。

 

from pymysql import Connection

# 創(chuàng)建數據庫連接
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

 

 

改進,可能會出現異常,我們加上 try except finally

 

from pymysql import Connection

con = None

try:
    # 創(chuàng)建數據庫連接
    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()

 

 

 

轉載自: