How to connect to mysql database using python?

by elise_daugherty , in category: MySQL , a year ago

How to connect to mysql database using python?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by lily , a year ago

@elise_daugherty 

To connect to a MySQL database using Python, follow these steps:

  1. Install the mysql-connector-python package using pip:
1
pip install mysql-connector-python


  1. Import the mysql.connector module:
1
import mysql.connector


  1. Establish a connection to the MySQL database using the connect() method, passing the required connection parameters (host, user, password, and database name):
1
2
3
4
5
6
cnx = mysql.connector.connect(
    host="localhost",
    user="username",
    password="password",
    database="database_name"
)


Replace "localhost", "username", "password", and "database_name" with the appropriate values according to your MySQL configuration.

  1. Create a cursor object to interact with the database:
1
cursor = cnx.cursor()


  1. Execute SQL queries using the execute() method of the cursor object:
1
cursor.execute("SELECT * FROM table_name")


Replace "table_name" with the name of the table you want to query.

  1. Fetch and process the results using the fetchall() method to retrieve all rows from the previous query:
1
2
3
result = cursor.fetchall()
for row in result:
    print(row)


You can also use other fetch methods like fetchone() or fetchmany() depending on your needs.

  1. Close the cursor and the database connection when done:
1
2
cursor.close()
cnx.close()


By following these steps, you can connect to a MySQL database using Python and perform various operations, such as executing queries and retrieving data.