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 do I use Python to authenticate MySQL on Windows?
- How can I avoid MySQL IntegrityError when using Python?
- How do I access MySQL using Python?
- How can I use Python and MySQL to generate a PDF?
- How can I compare and contrast using Python with MySQL versus PostgreSQL?
- How can I use Python to retrieve data from MySQL?
- How can I connect Python and MySQL?
- How can I use Python and MySQL to create a login system?
- How can I connect Python to a MySQL database?
- How can I use Python to interact with a MySQL database using YAML?
See more codes...