python-pymysql連接本地數(shù)據(jù)庫

一、下載第三方包pymysql

pip install pymysql

二、python代碼

"""
演示python pymysql庫的基本操作
"""

# 構(gòu)建到mysql數(shù)據(jù)庫的鏈接
from pymysql import Connection

# 創(chuàng)建對象實例 Connection是個類 關(guān)鍵字傳參
conn = Connection(
    host = "localhost", # 主機名
    port = 3306, # 端口號
    user = "root", # 賬戶名
    passwd = "root", # 密碼
)

# -------- 執(zhí)行非查詢性質(zhì)sql --------
# 獲取游標對象
cursor = conn.cursor()
# 選擇數(shù)據(jù)庫
conn.select_db('my_data_base')
# 執(zhí)行sql
# cursor.execute('create table py_student(id int, info varchar(255))')

# -------- 執(zhí)行查詢性質(zhì)sql --------
cursor.execute('select * from student')
result: tuple = cursor.fetchall() # 獲取全部數(shù)據(jù)fetch all
for r in result:
    print(r)
"""
運行結(jié)果:
(2, '周杰倫', 22, '女')
(3, '王五', 24, '男')
(4, '張三1', 25, '男')
(5, '李四2', 26, '女')
(6, '王五3', 27, '男')
"""

# 返回服務(wù)器的版本號
print(conn.get_server_info())
# 5.7.26


# 關(guān)閉鏈接
conn.close()

三、相關(guān)截圖

3.1 python執(zhí)行結(jié)果圖
image.png
3.2 數(shù)據(jù)庫執(zhí)行結(jié)果圖
image.png
image.png
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容