9951 explained code solutions for 126 technologies


python-mysqlHow can I connect to a MySQL database using Python?


  1. First, import the MySQL Connector Python module:

import mysql.connector

  1. Next, create a connection to the database by calling the connect() method of the mysql.connector module:
mydb = mysql.connector.connect(
  host="localhost",
  user="user",
  passwd="passwd"
)
  1. Create a cursor object using the cursor() method of the connection object:
mycursor = mydb.cursor()
  1. Use the execute() method of the cursor object to execute a SQL query. For example, to create a database:
mycursor.execute("CREATE DATABASE mydatabase")
  1. Use the commit() method of the connection object to commit the changes to the database:
mydb.commit()
  1. Finally, close the connection using the close() method of the connection object:
mydb.close()
  1. 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.

Edit this code on GitHub