【问题标题】:How to import sql.gz file to mysql database using python script?如何使用 python 脚本将 sql.gz 文件导入 mysql 数据库?
【发布时间】:2012-07-05 00:30:19
【问题描述】:

我使用 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 文件?

【问题讨论】:

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


    【解决方案1】:

    包含gzip 模块的内容。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-06-13
      • 2013-02-19
      • 2016-01-20
      • 2012-11-14
      • 2011-02-14
      • 2016-01-23
      • 1970-01-01
      • 2013-04-26
      相关资源
      最近更新 更多