9951 explained code solutions for 126 technologies


python-mysqlHow do I connect Python to a MySQL database using Visual Studio Code?


You can connect Python to a MySQL database using Visual Studio Code by following these steps:

  1. Install the Python extension for Visual Studio Code.
  2. Install the MySQL connector for Python.
  3. Open Visual Studio Code and create a new file.
  4. Enter the following code in the file:
import mysql.connector

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

print(mydb)

Output example

<mysql.connector.connection.MySQLConnection object at 0x7f5a0f3c1c50>
  1. Replace the “yourusername” and “yourpassword” with your MySQL credentials.
  2. Run the code by pressing the “Ctrl + F5” keys.
  3. If the connection is successful, you will get the output as shown above.

Helpful links

Edit this code on GitHub