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.connectormodule:
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 connect to MySQL using Python?
- How can I access MySQL using Python?
- How can I use Python and MySQL to generate a PDF?
- How do I connect Python with MySQL using XAMPP?
- How do I download MySQL-Python 1.2.5 zip file?
- How can I use Python and MySQL to create a login system?
- How to compile a MySQL-Python application for x86_64-Linux-GNU-GCC?
- How can I connect Python to a MySQL database?
- How can I use Python to yield results from a MySQL database?
- How do I check the version of MySQL I am using with Python?
See more codes...