How to Connect Python with MySQL?

Install MySQL Connector for Python: `pip install mysql-connector-python`

Import the library: `import mysql.connector`

Create a connection:

`conn = mysql.connector.connect(host=”localhost”, user=”root”, password=”your_password”, database=”your_db”)`

Check if the connection is successful:

`if conn.is_connected():`

Create a cursor:

`cursor = conn.cursor()`

Execute SQL queries:

`cursor.execute(“SELECT * FROM your_table”)`

Fetch results:

`rows = cursor.fetchall()`

Commit changes for INSERT, UPDATE, DELETE:

`conn.commit()`

Close the cursor:

`cursor.close()`

Close the connection:

`conn.close()`

Suggested for You

Trending Today