9951 explained code solutions for 126 technologies
To connect to MySQL using Python, you need to use a library such asmysql.connector.
The following example code can be used to connect to a MySQL database and execute a query:
import mysql.connectormydb = mysql.connector.connect( host="localhost", user="user", passwd="password")mycursor = mydb.cursor()mycursor.execute("SELECT * FROM customers")myresult = mycursor.fetchall()for x in myresult: print(x)
The output of the above code would be a list of all rows in the customers table.
The code consists of the following parts:
import mysql.connector
: This imports the mysql.connector library, which is used to connect to MySQL.
mydb = mysql.connector.connect(host="localhost", user="user", passwd="password")
: This creates a connection to the MySQL database. The host, user, and passwd parameters are used to specify the connection details.
mycursor = mydb.cursor()
: This creates a cursor object, which is used to execute queries.
mycursor.execute("SELECT * FROM customers")
: This executes the query to select all rows from the customers table.
myresult = mycursor.fetchall()
: This fetches all the results from the query.
for x in myresult: print(x)
: This prints out the results of the query.
For more information, see theMySQL Connector/Python documentation.