To connect to a MySQL database using Python, you need to do the following:
- Install the MySQL Python connector:
pip install mysql-connector-python
- Import the connector:
import mysql.connector
- Create a connection object:
cnx = mysql.connector.connect(user='username', password='password', host='hostname', database='database_name')
- Create a cursor object:
cursor = cnx.cursor()
Here is an example:
import mysql.connector
cnx = mysql.connector.connect(user='username', password='password', host='hostname', database='database_name')
cursor = cnx.cursor()
query = 'SELECT * FROM table_name'
cursor.execute(query)
for row in cursor:
print(row)
cursor.close()
cnx.close()
Make sure to replace
username
, password
, hostname
, database_name
, and table_name
with the appropriate values for your MySQL server.
Comments
Post a Comment