python連接數(shù)據(jù)庫
#%%
import pymysql
# 插入語句
# 打開數(shù)據(jù)庫連接
db = pymysql.connect(host="localhost", user="root", password="root", database="python",charset="utf8")
# 使用cursor()方法獲取操作游標
cursor = db.cursor()
# 數(shù)據(jù)列表
data = [(1,'張三','18'),
(2,'李四','19'),
(3,'王五','20'),
]
try:
# 執(zhí)行sql語句,插入多條數(shù)據(jù)
cursor.executemany("insert into test(id, name, score) values (%s,%s,%s)", data)
# 提交數(shù)據(jù)
db.commit()
except:
# 發(fā)生錯誤時回滾
db.rollback()
# 關(guān)閉數(shù)據(jù)庫連接
db.close()
# ======================================================================================== #
#%%
# 導入pymysql模塊
import pymysql
# 查詢單個數(shù)據(jù)
# 連接database,參數(shù)1主機名或IP;參數(shù)2:用戶名;參數(shù)3:密碼;參數(shù)4:數(shù)據(jù)庫名稱
conn = pymysql.connect(host="localhost", user="root", password="root", database="python",charset="utf8")
# 創(chuàng)建一個可以執(zhí)行SQL語句的光標對象
cursor = conn.cursor()
# 定義要執(zhí)行的SQL語句
sql = """
select * from test
"""
# 執(zhí)行SQL語句
cursor.execute(sql)
# 查詢單條數(shù)據(jù)
data = cursor.fetchone()
print(data);
# 關(guān)閉光標對象
cursor.close()
# 關(guān)閉數(shù)據(jù)庫連接
conn.close()








暫無數(shù)據(jù)