python-mysqlHow can I connect to a MySQL database using Python?
- First, import the MySQL Connector Python module:
import mysql.connector
- Next, create a connection to the database by calling the
connect()
method of themysql.connector
module:
mydb = mysql.connector.connect(
host="localhost",
user="user",
passwd="passwd"
)
- Create a cursor object using the
cursor()
method of the connection object:
mycursor = mydb.cursor()
- Use the
execute()
method of the cursor object to execute a SQL query. For example, to create a database:
mycursor.execute("CREATE DATABASE mydatabase")
- Use the
commit()
method of the connection object to commit the changes to the database:
mydb.commit()
- Finally, close the connection using the
close()
method of the connection object:
mydb.close()
- To test the connection, you can execute a SQL query such as
SELECT VERSION()
:
mycursor.execute("SELECT VERSION()")
# Output:
# 5.7.31-0ubuntu0.18.04.1
For more information, please refer to the MySQL Connector Python documentation.
More of Python Mysql
- How do I use Python to query MySQL with multiple conditions?
- How can I connect Python to a MySQL database?
- How can I use a while loop in Python to interact with a MySQL database?
- How can I convert data from a MySQL database to XML using Python?
- How do I use Python to authenticate MySQL on Windows?
- How can I use Python and MySQL to create a login system?
- How can I use Python to yield results from a MySQL database?
- How do Python MySQL and SQLite compare in terms of performance and scalability?
- How do I use Python to update multiple columns in a MySQL database?
- How can I use Python to insert a timestamp into a MySQL database?
See more codes...