python-mysqlHow do I execute a MySQL script using Python?
To execute a MySQL script using Python, you can use the mysql.connector
library. This library provides an API for connecting to and executing queries on a MySQL database.
An example of how to execute a MySQL script using Python is shown below:
import mysql.connector
# Connect to the database
mydb = mysql.connector.connect(
host="localhost",
user="username",
passwd="password",
database="database_name"
)
# Create a cursor object
mycursor = mydb.cursor()
# Execute the script
mycursor.execute("source /path/to/script.sql")
# Fetch the results
result = mycursor.fetchall()
# Print the results
print(result)
The code above will execute the SQL script located at /path/to/script.sql
and print the results.
The code above consists of the following parts:
import mysql.connector
: imports themysql.connector
library.mydb = mysql.connector.connect(...)
: connects to the MySQL database.mycursor = mydb.cursor()
: creates a cursor object.mycursor.execute("source /path/to/script.sql")
: executes the SQL script.result = mycursor.fetchall()
: fetches the results.print(result)
: prints the results.
Helpful links
More of Python Mysql
- How do I connect to XAMPP MySQL using Python?
- How do Python MySQL and SQLite compare in terms of performance and scalability?
- How can I install the MySQL-Python (Python 2.x) module?
- How do I download MySQL-Python 1.2.5 zip file?
- How can I connect Python to a MySQL database?
- How do I use Python to update multiple columns in a MySQL database?
- How do I use Python to query MySQL with multiple conditions?
- How do I use Python to authenticate MySQL on Windows?
- How do I use a Python MySQL refresh cursor?
- How do I use a cursor to interact with a MySQL database in Python?
See more codes...