9951 explained code solutions for 126 technologies


python-mysqlHow do I install the Python MySQL Connector?


  1. Installing the Python MySQL Connector is easy with the help of the pip package manager.
  2. Open a terminal window and type the following command: pip install mysql-connector-python
  3. This will install the connector and all of its dependencies.
  4. To test the installation, try connecting to a MySQL database with the following code:
import mysql.connector

mydb = mysql.connector.connect(
  host="localhost",
  user="yourusername",
  passwd="yourpassword"
)

print(mydb)

Output example

<mysql.connector.connection_cext.CMySQLConnection object at 0x7f7fb7f2c7f0>
  1. The above code connects to a MySQL database using the credentials provided and returns a connection object.
  2. If you get an error, check out the documentation for more information on how to set up the connection.
  3. You can also find more examples of how to use the connector here.

Edit this code on GitHub