简体   繁体   English

如何使用 mysql 连接器执行 a.sql 文件并将其保存在 python 的数据库中?

[英]How to execute a .sql file using mysql connector and save it in a database in python?

I have a.sql file and I want to know if we can execute it directly in python using mysql.connector python class provided my mysql community.我有一个 .sql 文件,我想知道我们是否可以使用我的 mysql 社区提供的 mysql.connector python 类直接在 python 中执行它。

Usually I can execute the.sql file in mysql server in terminal using these queries,通常我可以使用这些查询在终端的 mysql 服务器中执行 .sql 文件,

CREATE DATABASE test;
USE test;
source data.sql;

but I want to do it in python directly.但我想直接在 python 中完成。 Is it possible?可能吗?

Yes you just need to read the file then execute the string contents on the cursor ... something like this是的,你只需要读取文件然后execute cursor上的字符串内容......就像这样

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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM