Python知識(shí)分享網(wǎng) - 專業(yè)的Python學(xué)習(xí)網(wǎng)站 學(xué)Python,上Python222
pymysql創(chuàng)建數(shù)據(jù)庫連接
匿名網(wǎng)友發(fā)布于:2023-09-19 10:36:01
(侵權(quán)舉報(bào))

1小時(shí)學(xué)會(huì) Python操作Mysql數(shù)據(jù)庫之pymysql模塊技術(shù)https://www.bilibili.com/video/BV1Dz4y1j7Jr

 

 

 

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

 

from pymysql import Connection

# 創(chuàng)建數(shù)據(jù)庫連接
con = Connection(
    host="localhost",  # 主機(jī)名
    port=3306,  # 端口
    user="root",  # 賬戶
    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ù)庫連接
    con = Connection(
        host="localhost",  # 主機(jī)名
        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:
        # 關(guān)閉連接
        con.close()

 

 

 

轉(zhuǎn)載自: