【问题标题】:Running SQL file from Python从 Python 运行 SQL 文件
【发布时间】:2017-10-07 11:27:33
【问题描述】:

我必须启动一个 python sql 文件。 该文件用于mysql。 我试过这样:

from subprocess import Popen, PIPE
import sys


class ImportSql:
    def execImport(self, fileSql):
        try:
            with open(fileSql, 'r') as fileInput:
                proc = Popen(["mysql", "DB_NAME", "-u", "USER", "-pPASSWORD"], stdin=PIPE, stdout=PIPE)
                proc.communicate('source ' + fileInput)[0]
        except BaseException as ex:
            print("ERROR:", ex)
            sys.exit()

但我收到此错误:

错误:必须是 str,而不是 _io.TextIOWrapper

我该怎么办?

【问题讨论】:

标签: python mysql sql mariadb popen


【解决方案1】:

您需要传递文件的内容,而不是文件对象。

proc.communicate('source ' + fileInput.read())

另外,请不要捕获异常只是为了打印它们并退出。这就是 Python 已经做的事情。省去那个 try/except。

【讨论】:

    【解决方案2】:

    好的,我将 mysql 指令移到了一个 bat 中。

    from subprocess import Popen
    
    
    class ImportSql:
        def execImport(self):
            p = Popen("import.bat")
            p.communicate()
    

    没关系! 谢谢!

    【讨论】:

      猜你喜欢
      • 2020-11-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-29
      • 2013-11-14
      相关资源
      最近更新 更多