我有一个 .sql 文件,我想知道我们是否可以使用我的 mysql 社区提供的 mysql.connector python 类直接在 python 中执行它。
通常我可以使用这些查询在终端中执行 mysql 服务器中的 .sql 文件,
CREATE DATABASE test;
USE test;
source data.sql;
Run Code Online (Sandbox Code Playgroud)
但我想直接用python来做。是否可以?
Yes you just need to read the file then execute the string contents on the cursor... something like this
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
passwd="yourpassword"
)
with open('something.sql', 'r') as f:
with mydb.cursor() as cursor:
cursor.execute(f.read(), multi=True)
mydb.commit()
Run Code Online (Sandbox Code Playgroud)