python - 如何使用python脚本将sql.gz文件导入mysql数据库?

标签 python file-io python-2.7 mysql mysql-python

我使用 python 脚本以 sql.gz 格式使用 mysqldump 导出数据库。如何使用此 Python 脚本导入 sql.gz 文件?

我编写了适用于 .sql.txt 文件的代码。

import MySQLdb


filename = self.ui.txtFileLocationImport.text()

# Open database connection
db = MySQLdb.connect(dbHostName, dbUser, dbPassword, databaseName)

# prepare a cursor object using cursor() method
cursor = db.cursor()

#Prepare SQL query to INSERT a record into the database.
f = open(filename , 'r')
try:
    cursor.execute('SET foreign_key_checks = 0')
    for sql in f:
        if sql == '\n' or sql[0] == '/':
            pass
        else:
            # Execute the SQL command
            cursor.execute(str(sql))

    #Commit your changes in the database
    cursor.execute('SET foreign_key_checks = 1')
    db.commit()
except Exception as e:
   print e
   # Rollback in case there is any error
   db.rollback()

#close file
f.close()
# disconnect from server
db.close()

这仅适用于 .txt.sql 文件。我怎样才能让它读取 sql.gz 文件?

最佳答案

gzip的内容模块。

关于python - 如何使用python脚本将sql.gz文件导入mysql数据库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11330159/

相关文章:

python - 为什么 unittest 中的断言使用 TestCase.assertEqual 而不是 assert 关键字?

Python 统计 : how do I write it to a (human readable) file

java - BufferedReader.ready() 方法是否确保 readLine() 方法不返回 NULL?

python - 获取 Soundcloud 桌面应用程序的访问 token ?

windows-7 - Pyinstaller,如何在 32 位 linux 上制作 32 位和 64 位 .exe?

python - Dask add_done_callback 与其他参数?

python - 如何在 python 中发送 POST 请求并获得正确的 json 响应?

python - 单元测试数据库访问层

c++ - 在 C++ 中从文件末尾读取最有效的方法是什么? (解析文件中的最后 128 位)

python-2.7 - 了解 Python 中一行中的多个变量赋值