pycharm連接MySQL

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

相關(guān)閱讀更多精彩內(nèi)容

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