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 can I use Python to retrieve data from MySQL?
- How can I connect to MySQL using Python?
- How do I use a SELECT statement in Python to query a MySQL database?
- How can I connect Python and MySQL?
- How can I connect Python to a MySQL database?
- How do I use Python to query MySQL with multiple conditions?
- How can I use Python to interact with a MySQL database using YAML?
- How can I avoid MySQL IntegrityError when using Python?
- How do I format a date in MySQL using Python?
- How do I use Python to authenticate MySQL on Windows?
See more codes...