1.安裝pymysql
pip3 install pymysql
2.導(dǎo)入模塊
import pymysql
python 連接mysql的步驟
1.建立連接
con = pymysql.connect(...)
2.獲取操作游標(biāo)
cursor = con.cursor
3.執(zhí)行sql語句
cursor.execute(sql)
4.查詢結(jié)果
5.關(guān)閉連接
eg:
import pymysql
client = pymysql.Connect(user="root",
password="123",
host="127.0.0.1",
port=3306,
db="db",
charset="utf8")
#游標(biāo)
cursor = client.cursor()
#默認(rèn)是begin
def show_tables():
result = cursor.execute("show tables;")
real_res = cursor.fetchall()
print(real_res)
def my_sw():
try:
# 你的代碼
cursor.execute("UPDATE staff SET salary=10 WHERE id=4;")
cursor.execute("UPDATE staff SET salary=20 WHERE id=5")
except Exception as e:
client.rollback()
else:
client.commit()
def get_data(staff_id):
sql = "select * from staff where id={sid}".format(sid=int(staff_id))
# sql = "select * from staff where id=" + str(sid)
# sql = "select * from staff where id=%s" % int(staff_id)
cursor.execute(sql)
res = cursor.fetchone()
print(res)
def fetch_dict(cursor):
cols = [i[0] for i in cursor.description]
return [dict(zip(cols, row)) for row in cursor.fetchall()]
def get_datas():
sql = "select * from staff"
cursor.execute(sql)
res = fetch_dict(cursor)
print(res)
if __name__ == "__main__":
# my_sw()
get_datas()
cursor.fetchone()在結(jié)果集內(nèi)拿一個(gè)數(shù)據(jù)
cursor.fetchall()在結(jié)果集內(nèi)拿全部
cursor.fetchmany(size)可以拿指定個(gè)數(shù)的結(jié)果
將結(jié)果集以數(shù)組結(jié)合字典的形式返回
def fetch_dict(cursor):
cols = [i[0] for i in cursor.description]
return [dict(zip(cols, row)) for row in cursor.fetchall()]