📅  最后修改于: 2023-12-03 15:33:42.019000             🧑  作者: Mango
If you are a Python developer and you need to interact with a MySQL database, then you will likely need the mysql-connector Python module. The mysql-connector Python module is used to connect to a MySQL database and perform various database operations.
To install mysql-connector using pip, you simply need to run the following command:
pip install mysql-connector
This will download and install the mysql-connector Python module to your system.
Before you can use the mysql-connector Python module, you will need to have the following prerequisites in place:
Once you have installed the mysql-connector Python module, you can start using it in your Python code. To use mysql-connector, you will need to first import it at the top of your Python file:
import mysql.connector
Next, you will need to create a connection to your MySQL database using the connect()
method:
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)
You can then create a cursor object to perform database operations:
mycursor = mydb.cursor()
From here, you can perform various database operations, such as executing SQL queries, inserting data, updating data, and deleting data.
# Select data from a table
mycursor.execute("SELECT * FROM customers")
myresult = mycursor.fetchall()
for x in myresult:
print(x)
# Insert data into a table
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
val = ("John", "Highway 21")
mycursor.execute(sql, val)
mydb.commit()
print(mycursor.rowcount, "record inserted.")
For more information on how to use mysql-connector, refer to the official documentation: https://dev.mysql.com/doc/connector-python/en/