how to connect python to mysql using mysql-connector-python
Firstly, You need to download mysql and set the required confiquration and then to connect to a MySQL database from Python, you will need to use a library such as mysql-connector-python or PyMySQL. Here's an example of how you can use mysql-connector-python to connect to a MySQL database:
import mysql.connector
cnx = mysql.connector.connect(
host="host_name",
user="user_name",
password="password",
database="database_name"
)
cursor = cnx.cursor()
query = "SELECT * FROM table_name"
cursor.execute(query)
result = cursor.fetchall()
for row in result:
print(row)
cnx.close()
Replace host_name, user_name, password, database_name, and table_name with the appropriate values for your database.
import pymysql
cnx = pymysql.connect(
host="host_name",
user="user_name",
password="password",
database="database_name"
)
cursor = cnx.cursor()
query = "SELECT * FROM table_name"
cursor.execute(query)
result = cursor.fetchall()
for row in result:
print(row)
cnx.close()
Both of these libraries allow you to perform various operations on a MySQL database, such as running queries, committing transactions, and more.
Comments
Post a Comment