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

时间:2012-07-04 13:33:29

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

我使用python脚本以mysqldump格式使用sql.gz导出数据库。如何使用此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文件?

1 个答案:

答案 0 :(得分:1)

使用gzip模块的内容。