pycharm连接MySQL

1.安装pymysql
pip3 install pymysql
2.导入模块
import pymysql
python 连接mysql的步骤

1.建立连接
con = pymysql.connect(...)
2.获取操作游标
cursor = con.cursor
3.执行sql语句
cursor.execute(sql)
4.查询结果
5.关闭连接
eg:

import pymysql

client = pymysql.Connect(user="root",
                         password="123",
                         host="127.0.0.1",
                         port=3306,
                         db="db",
                          charset="utf8")
#游标
cursor = client.cursor()

#默认是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()在结果集内拿一个数据

cursor.fetchall()在结果集内拿全部

cursor.fetchmany(size)可以拿指定个数的结果

将结果集以数组结合字典的形式返回

def fetch_dict(cursor):
    cols = [i[0] for i in cursor.description]
    return [dict(zip(cols, row)) for row in cursor.fetchall()]

你可能感兴趣的:(pycharm连接MySQL)