简体   繁体   中英

Automate backup and deletion of Microsoft sql database using python

So what I need to do is to backup my Microsoft Sql database and delete 6 month old data from the DB. Both of these processes must be automated. Right now I am stuck at the backup. I have been studying different things and tried to apply them, but most of the help that I have found is regarding database systems other than that of microsoft sql.

for instance I have found the following code

for db_name in db_names:
try:
    file_path = ''
    dumper = " -U %s --password -Z 9 -f %s -F c %s  "
   os.putenv('PGPASSWORD', db_password)
    bkp_file = '%s_%s.sql' % (db_name, time.strftime('%Y%m%d_%H_%M_%S'))
    glob_list = glob.glob(dump_dir + db_name + '*' + '.pgdump')
    file_path = os.path.join(dump_dir, bkp_file)
    command = 'pg_dump' + dumper % (db_username, file_path, db_name)
    subprocess.call(command, shell=True)
    subprocess.call('gzip ' + file_path, shell=True)
except:
    print("Couldn't backup database" % (db_name))

The above code gives me the following errors

'sqldumper' is not recognized as an internal or external command,
 operable program or batch file.
'gzip' is not recognized as an internal or external command,
 operable program or batch file.

I think this is happening because this method is for postgres sql data.

Any guideline or tutorial or help of any other sort is highly appreciated.

For MS SQL you can adapt your code for this command:

sqlcmd -S localhost -U SA -Q "BACKUP DATABASE [demodb] TO DISK = N'/var/opt/mssql/data/demodb.bak' WITH NOFORMAT, NOINIT, NAME = 'demodb-full', SKIP, NOREWIND, NOUNLOAD, STATS = 10"

More information can be found here: https://docs.microsoft.com/en-us/sql/linux/sql-server-linux-backup-and-restore-database?view=sql-server-ver15

I'd like to know, how you are running the python script. those errors you are getting, likely from windows command prompt. Make sure you are importing the gzip module in your python code above. Here's one example for MySQL: [Python Script for MySQL Database Backup][1] [1]: https://tecadmin.net/python-script-for-mysql-database-backup/

later on, for automating the script if you are using Linux, you can use cron job to run it anytime you want. For windows you can use Windows Task Scheduler.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM