无法使用 Python mysqldb 模块使 MySQL 源查询正常工作

2022-01-04 00:00:00 python mysql scripting

我有以下几行代码:

sql = "source C:\My Dropbox\workspace\projects\hosted_inv\create_site_db.sql"
cursor.execute (sql)

当我执行我的程序时,出现以下错误:

When I execute my program, I get the following error:

错误 1064:您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以在第 1 行的源 C:My Dropboxworkspaceprojectshosted_invcreate_site_db.sql"附近​​使用正确的语法

Error 1064: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'source C:My Dropboxworkspaceprojectshosted_invcreate_site_db.sql' at line 1

现在我可以将以下内容作为查询复制并粘贴到 mysql 中:

Now I can copy and past the following into mysql as a query:

source C:\My Dropbox\workspace\projects\hosted_inv\create_site_db.sql

它完美无缺.当我检查脚本执行的查询的查询日志时,它显示我的查询如下:

And it works perfect. When I check the query log for the query executed by my script, it shows that my query was the following:

source C:\My Dropbox\workspace\projects\hosted_inv\create_site_db.sql

但是,当我手动将其粘贴并执行时,整个 create_site_db.sql 在查询日志中展开并显示该文件中的所有 sql 查询.

However, when I manually paste it in and execute, the entire create_site_db.sql gets expanded in the query log and it shows all the sql queries in that file.

我是否遗漏了有关 mysqldb 如何查询的内容?我是否遇到了限制.我的目标是运行一个 sql 脚本来创建架构结构,但我不想在 shell 进程中调用 mysql 来获取 sql 文件.

Am I missing something here on how mysqldb does queries? Am I running into a limitation. My goal is to run a sql script to create the schema structure, but I don't want to have to call mysql in a shell process to source the sql file.

有什么想法吗?谢谢!

推荐答案

正如其他人所说,你不能在 MySQLdb Python API 中使用命令 source

As others said, you cannot use the command source in MySQLdb Python API

因此,与其运行它,不如加载文件并执行它

So, instead of running that, load the file and execute it

假设您的 .sql 文件有

Lets say your .sql file has

create database test;

阅读内容如

sql=open("test.sql").read()

然后执行它

cursor.execute(sql);

您将获得新的数据库test"

You will get new database "test"

相关文章