python-mysqlHow can I connect to MySQL using Python?
To connect to MySQL using Python, you need to use a library such as mysql.connector.
The following example code can be used to connect to a MySQL database and execute a query:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="user",
passwd="password"
)
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM customers")
myresult = mycursor.fetchall()
for x in myresult:
print(x)
The output of the above code would be a list of all rows in the customers table.
The code consists of the following parts:
-
import mysql.connector
: This imports the mysql.connector library, which is used to connect to MySQL. -
mydb = mysql.connector.connect(host="localhost", user="user", passwd="password")
: This creates a connection to the MySQL database. The host, user, and passwd parameters are used to specify the connection details. -
mycursor = mydb.cursor()
: This creates a cursor object, which is used to execute queries. -
mycursor.execute("SELECT * FROM customers")
: This executes the query to select all rows from the customers table. -
myresult = mycursor.fetchall()
: This fetches all the results from the query. -
for x in myresult: print(x)
: This prints out the results of the query.
For more information, see the MySQL Connector/Python documentation.
More of Python Mysql
- How can I connect to a MySQL database over SSH using Python?
- How can I use Python to retrieve data from MySQL?
- How can I connect Python and MySQL?
- How do I access MySQL using Python?
- How can I use Python and MySQL to create a login system?
- How do I use a cursor to interact with a MySQL database in Python?
- How do Python and MySQL compare to MariaDB?
- How can I keep a MySQL connection alive in Python?
- ¿Cómo conectar Python a MySQL usando ejemplos?
See more codes...