VS怎么連接MySQL數(shù)據(jù)庫

小億
94
2024-01-25 09:50:09
欄目: 云計(jì)算

要連接MySQL數(shù)據(jù)庫,首先需要安裝MySQL數(shù)據(jù)庫驅(qū)動(dòng)程序。在Python中,可以使用pymysqlmysql-connector-python等庫來連接MySQL數(shù)據(jù)庫。

以下是使用pymysql庫連接MySQL數(shù)據(jù)庫的步驟:

  1. 安裝pymysql庫:

    pip install pymysql
    
  2. 導(dǎo)入pymysql庫:

    import pymysql
    
  3. 建立數(shù)據(jù)庫連接:

    conn = pymysql.connect(
        host='localhost',  # 數(shù)據(jù)庫主機(jī)地址
        port=3306,         # 數(shù)據(jù)庫端口號(hào),默認(rèn)為3306
        user='root',       # 數(shù)據(jù)庫用戶名
        password='password',   # 數(shù)據(jù)庫密碼
        db='database_name',     # 數(shù)據(jù)庫名
        charset='utf8mb4',  # 字符集
        cursorclass=pymysql.cursors.DictCursor  # 游標(biāo)類型,這里使用字典類型的游標(biāo)
    )
    
  4. 創(chuàng)建游標(biāo)對(duì)象:

    cursor = conn.cursor()
    
  5. 執(zhí)行SQL查詢:

    cursor.execute("SELECT * FROM table_name")
    result = cursor.fetchall()
    
  6. 關(guān)閉游標(biāo)和數(shù)據(jù)庫連接:

    cursor.close()
    conn.close()
    

這樣就可以連接上MySQL數(shù)據(jù)庫并執(zhí)行SQL查詢了。根據(jù)具體的需求,可以進(jìn)一步根據(jù)pymysql庫提供的方法來插入、更新、刪除數(shù)據(jù)等操作。

0