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 connect Python and MySQL?
- How do I use Python to authenticate MySQL on Windows?
- How do I use Python to query MySQL with multiple conditions?
- How can I connect Python to a MySQL database?
- How to compile a MySQL-Python application for x86_64-Linux-GNU-GCC?
- How do I use a cursor to interact with a MySQL database in Python?
- How can I use a MySQL variable in Python?
- How can I use Python to perform an upsert on a MySQL database?
- How can I use Python to insert a timestamp into a MySQL database?
See more codes...