一裁替、下載第三方包pymysql
pip install pymysql
二、python代碼
"""
演示python pymysql庫的基本操作
"""
# 構(gòu)建到mysql數(shù)據(jù)庫的鏈接
from pymysql import Connection
# 創(chuàng)建對(duì)象實(shí)例 Connection是個(gè)類 關(guān)鍵字傳參
conn = Connection(
host = "localhost", # 主機(jī)名
port = 3306, # 端口號(hào)
user = "root", # 賬戶名
passwd = "root", # 密碼
)
# -------- 執(zhí)行非查詢性質(zhì)sql --------
# 獲取游標(biāo)對(duì)象
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)
"""
運(yùn)行結(jié)果:
(2, '周杰倫', 22, '女')
(3, '王五', 24, '男')
(4, '張三1', 25, '男')
(5, '李四2', 26, '女')
(6, '王五3', 27, '男')
"""
# 返回服務(wù)器的版本號(hào)
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