在Python中操作MySQL數(shù)據(jù)庫,可以使用官方提供的mysql-connector-python
庫或者第三方庫pymysql
。
下面以mysql-connector-python
庫為例,介紹如何操作MySQL數(shù)據(jù)庫:
安裝mysql-connector-python
庫:在命令行中運(yùn)行pip install mysql-connector-python
。
導(dǎo)入mysql.connector
模塊。
建立數(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ù)庫名。
cursor = cnx.cursor()
# 查詢數(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)
cnx.commit()
cursor.close()
cnx.close()
以上就是在Python中使用mysql-connector-python
庫操作MySQL數(shù)據(jù)庫的基本步驟。