溫馨提示×

python中怎么操作mysql數(shù)據(jù)庫

小億
95
2024-02-04 15:47:41
欄目: 云計(jì)算

在Python中操作MySQL數(shù)據(jù)庫,可以使用官方提供的mysql-connector-python庫或者第三方庫pymysql。

下面以mysql-connector-python庫為例,介紹如何操作MySQL數(shù)據(jù)庫:

  1. 安裝mysql-connector-python庫:在命令行中運(yùn)行pip install mysql-connector-python

  2. 導(dǎo)入mysql.connector模塊。

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

import mysql.connector

# 建立數(shù)據(jù)庫連接
cnx = mysql.connector.connect(
    host="localhost",
    user="username",
    password="password",
    database="database_name"
)

其中host為MySQL服務(wù)器地址,user為用戶名,password為密碼,database為數(shù)據(jù)庫名。

  1. 創(chuàng)建游標(biāo)對象:
cursor = cnx.cursor()
  1. 執(zhí)行SQL語句:
# 查詢數(shù)據(jù)
query = "SELECT * FROM table_name"
cursor.execute(query)

# 插入數(shù)據(jù)
insert_query = "INSERT INTO table_name (column1, column2) VALUES (%s, %s)"
data = ("value1", "value2")
cursor.execute(insert_query, data)

# 更新數(shù)據(jù)
update_query = "UPDATE table_name SET column1 = %s WHERE column2 = %s"
data = ("new_value", "condition_value")
cursor.execute(update_query, data)

# 刪除數(shù)據(jù)
delete_query = "DELETE FROM table_name WHERE condition_column = %s"
data = ("condition_value",)
cursor.execute(delete_query, data)
  1. 提交事務(wù):
cnx.commit()
  1. 關(guān)閉游標(biāo)和數(shù)據(jù)庫連接:
cursor.close()
cnx.close()

以上就是在Python中使用mysql-connector-python庫操作MySQL數(shù)據(jù)庫的基本步驟。

0