python-mysqlHow can I connect to a MySQL database using Python?
-
Install the MySQL Connector/Python package:
pip install mysql-connector-python
-
Establish a connection to the MySQL database by creating a new
MySQLConnection
object:import mysql.connector mydb = mysql.connector.connect( host="localhost", user="yourusername", passwd="yourpassword" )
-
Create a new
MySQLCursor
object from the connection:mycursor = mydb.cursor()
-
Use the
execute()
method of the cursor object to execute a MySQL query:mycursor.execute("SELECT * FROM customers")
-
Fetch all the rows from the cursor object using the
fetchall()
method:myresult = mycursor.fetchall() for x in myresult: print(x)
Output:
(1, 'John', 'Highway 21') (2, 'Peter', 'Lowstreet 4') (3, 'Amy', 'Apple st 652') (4, 'Hannah', 'Mountain 21')
-
Close the cursor and connection objects, once your work is finished:
mycursor.close() mydb.close()
-
For more information on connecting to a MySQL database using Python, please refer to the official MySQL Connector/Python documentation.
More of Python Mysql
- How can I use Python and MySQL to generate a PDF?
- How can I connect Python to a MySQL database?
- How can I connect Python to a MySQL database using an Xserver?
- How can I connect Python and MySQL?
- How do Python and MySQL compare to MariaDB?
- How do I use Python to update multiple columns in a MySQL database?
- How do I connect Python with MySQL using XAMPP?
- How can I connect to MySQL using Python?
- How do I use Python to authenticate MySQL on Windows?
- How can I convert a MySQL database to a SQLite database using Python?
See more codes...