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 access MySQL using Python?
- ¿Cómo conectar Python a MySQL usando ejemplos?
- How can I connect Python to a MySQL database?
- How do I access MySQL using Python?
- How can I convert data from a MySQL database to XML using Python?
- How do I set up a secure SSL connection between Python and MySQL?
- How do I download MySQL-Python 1.2.5 zip file?
- How can I connect to MySQL using Python?
- How do I use Python to connect to a MySQL database using XAMPP?
- How can I connect Python and MySQL?
See more codes...