python-mysqlHow do I connect Python with MySQL using XAMPP?
In order to connect Python with MySQL using XAMPP, you need to install MySQL Connector Python module. MySQL Connector Python is the official Oracle-supported driver to connect MySQL through Python.
First, install the MySQL Connector Python module:
pip install mysql-connector-python
Next, create a connection object to the MySQL server, using the connection credentials.
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
passwd="yourpassword"
)
print(mydb)
# output: <mysql.connector.connection_cext.CMySQLConnection object at 0x7f3a4c3b4550>
Finally, create a cursor object to execute SQL queries.
mycursor = mydb.cursor()
mycursor.execute("SHOW DATABASES")
for x in mycursor:
print(x)
# output: ('information_schema',)
# ('mysql',)
# ('performance_schema',)
# ('sakila',)
# ('sys',)
# ('world',)
The following are the parts of the code and their explanation:
pip install mysql-connector-python
- This command installs the MySQL Connector Python module.import mysql.connector
- This command imports the MySQL Connector Python module.mydb = mysql.connector.connect(host="localhost", user="yourusername", passwd="yourpassword")
- This command creates a connection object to the MySQL server, using the connection credentials.mycursor = mydb.cursor()
- This command creates a cursor object to execute SQL queries.mycursor.execute("SHOW DATABASES")
- This command executes the SQL query to show the databases.for x in mycursor: print(x)
- This command prints the output of the SQL query.
Helpful links
More of Python Mysql
- How can I use Python to interact with a MySQL database using YAML?
- How can I use Python to retrieve data from MySQL?
- ¿Cómo conectar Python a MySQL usando ejemplos?
- How can I connect Python to a MySQL database?
- How can I use Python and MySQL to generate a PDF?
- How can I use Python to yield results from a MySQL database?
- How do I use Python to query MySQL with multiple conditions?
- How do I install a Python package from PyPI into a MySQL database?
- How can I connect Python to a MySQL database using an Xserver?
- How do I access MySQL using Python?
See more codes...