MySQL with Python: Complete Guide
In Python, you can interact with MySQL databases using either the official mysql-connector-python library or the third-party library pymysql.
“Here is an example using the mysql-connector-python library to demonstrate how to manipulate a MySQL database.”
- To install the mysql-connector-python library, simply run ‘pip install mysql-connector-python’ in the command line.
- Import the mysql.connector module.
- Establish database connection:
import mysql.connector
# 建立数据库连接
cnx = mysql.connector.connect(
host="localhost",
user="username",
password="password",
database="database_name"
)
The host is the address of the MySQL server, the user is the username, the password is the password, and the database is the name of the database.
- Create a cursor object:
cursor = cnx.cursor()
- Execute SQL statement.
# 查询数据
query = "SELECT * FROM table_name"
cursor.execute(query)
# 插入数据
insert_query = "INSERT INTO table_name (column1, column2) VALUES (%s, %s)"
data = ("value1", "value2")
cursor.execute(insert_query, data)
# 更新数据
update_query = "UPDATE table_name SET column1 = %s WHERE column2 = %s"
data = ("new_value", "condition_value")
cursor.execute(update_query, data)
# 删除数据
delete_query = "DELETE FROM table_name WHERE condition_column = %s"
data = ("condition_value",)
cursor.execute(delete_query, data)
- “Submit transaction:”
cnx.commit()
- Close the cursor and the database connection.
cursor.close()
cnx.close()
The above are the basic steps for using the mysql-connector-python library to operate a MySQL database in Python.