Sei sulla pagina 1di 8

02/06/14

How to backup multiple databases using Perl - CodeProject

ArticlesDatabaseDatabaseGeneral

HowtobackupmultipledatabasesusingPerl
ByCarlosLuis,7Jan2012
5.00(1vote)

Introduction
Duringthelast5months,IhavebeenlearningPerl,soIdecidedtocreateagenericscripttobackup
severaldatabases,andbeabletouseitfromotherlanguagesaswell.

Aboutthescript:
Thefollowingscriptwillcreateandexecuteacommandlinewiththeuserprovidedoptionsforthespecified
databaseintheoptionengine.Thefinalresultwillbeabackupfilestoredinthepathyouprovidedinthe
optiondir.
Inordertoexecutethescriptfromacommandline,youjustneedtocreatethecommandlineanddefine
therequiredoptions,Example:
perlbackup.plutility="C:\ProgramFiles(x86)\PostgreSQL\9.0\bin\pg_dump.exe"engine=postgres
host=localhostport=5432dbname=testuser=dbuserpassword=user'spassworddir="D:\backup"
Tobackupanotherdatabase,youjustneedtochangetheengineoptionandsettheotheroptions.

Scriptcode
#
#Package
#backup.pl
#
#Purpose
#CreatesbackupfilesforMySQL,SQLServer,OracleandPostgreSQL
#
#Engineer
#CarlosLuisRojasAragones

www.codeproject.com/Tips/308309/How-to-backup-multiple-databases-using-Perl?display=Print

1/8

02/06/14

How to backup multiple databases using Perl - CodeProject

#
#
packagebackup

#
#Includes
#
useutf8
usestrict
usewarnings
useGetopt::Long

#
#Variables
#
my$utility
my$dbName
my$host
my$port
my$dbEngine
my$destinationPath
my$user
my$password

#
#ReadOptions
#
GetOptions(
"utility=s"=>\$utility,
"engine=s"=>\$dbEngine,
"host=s"=>\$host,
"port=i"=>\$port,
"dbname=s"=>\$dbName,
"user=s"=>\$user,
"password=s"=>\$password,
"dir=s"=>\$destinationPath,
)ordie

submain{
my@args=()
if($dbEngineeq"mysql"){
@args=mysqlCommandLine()
}elsif($dbEngineeq"sqlserver"){
@args=sqlserverCommandLine()
}elsif($dbEngineeq"oracle"){
@args=oracleCommandLine()
}elsif($dbEngineeq"postgres"){
@args=postgresCommandLine()
}

if(@args>0){
my$commandLine=createCommandLine(\@args)
print$commandLine
my$result=qx{$commandLine}
print$result
}else{
print"Unabletobackupthedatabase"
exit1

www.codeproject.com/Tips/308309/How-to-backup-multiple-databases-using-Perl?display=Print

2/8

02/06/14

How to backup multiple databases using Perl - CodeProject

}
return
}

#
#Mysql
#
submysqlCommandLine{
my@args=()

if($utility&&$utilityne""){
push(@args,'"'.$utility.'"')
}

if($host&&$hostne""){
push(@args,qq{h"$host"})
}

if($user&&$userne''){
push(@args,qq{u"$user"})
}

if($password&&$passwordne''){
push(@args,qq{p"$password"})
}

if($port&&$portne''){
push(@args,qq{P$port})
}

if($dbName&&$dbNamene''){
push(@args,$dbName)
}

if($destinationPath&&$destinationPathne''){
if(!($destinationPath=~m/\.sql/)){
$destinationPath.=".sql"
}
push(@args,qq{>"$destinationPath"})
}

return@args
}

#
#SqlServer
#
subsqlserverCommandLine{
my$backupStatement="BACKUPDATABASE"
my@args=()

if($utility&&$utilityne""){
push(@args,'"'.$utility.'"')
}
if($user&&$userne''){
push(@args,qq{U"$user"})
}

www.codeproject.com/Tips/308309/How-to-backup-multiple-databases-using-Perl?display=Print

3/8

02/06/14

How to backup multiple databases using Perl - CodeProject

if($password&&$passwordne''){
push(@args,qq{P"$password"})
}

if($dbName&&$dbNamene''){
push(@args,qq{d$dbName})
$backupStatement.="$dbNameTODISK='"
}

if($host&&$hostne""){
push(@args,qq{S"$host"})
}

if($destinationPath&&$destinationPathne''){
if(!($destinationPath=~m/\.dat/)){
$destinationPath.=".dat"
}
$backupStatement.=$destinationPath
}

if($backupStatement&&$backupStatementne''){
push(@args,qq{Q"$backupStatement'"})
}

return@args
}

#
#Oracle
#
suboracleCommandLine{
my@args=()
my$authString=""
if($utility&&$utilityne''){
push(@args,'"'.$utility.'"')
}

if($user&&$userne''){
$authString="userid=$user"
}

if($password&&$passwordne''){
if($host&&$hostne""){
$authString.="/$password@".$host
}else{
$authString.="/$password"
}
}

if($authString&&$authStringne''){
push(@args,$authString)
}

if($destinationPath&&$destinationPathne''){
#dumpfile
if(!($destinationPath=~m/\.dmp/)){
$destinationPath.=".dmp"
}

www.codeproject.com/Tips/308309/How-to-backup-multiple-databases-using-Perl?display=Print

4/8

02/06/14

How to backup multiple databases using Perl - CodeProject

push(@args,qq{file='$destinationPath'})
#logfile
$destinationPath=~s/.dmp/.log/
push(@args,qq{log='$destinationPath'})
}

if($user&&$userne''){
push(@args,"owner=$user")
}

push(@args,qq{statistics="none"})

return@args
}

#
#Postgres
#
subpostgresCommandLine{
my@args=()

if($utility&&$utilityne""){
push(@args,'"'.$utility.'"')
}

if($host&&$hostne""){
push(@args,qq{host$host})
}

if($port&&$portne''){
push(@args,qq{port$port})
}

if($user&&$userne''){
push(@args,qq{username$user})
}

if($password&&$passwordne''){
#weneedtosetthePGPASSWORDenvironmentvariable
$ENV{'PGPASSWORD'}=$password
}

push(@args,"formatcustomblobsverbose")

if($destinationPath&&$destinationPathne''){
if(!($destinationPath=~m/\.backup/)){
$destinationPath.=".backup"

}
push(@args,qq{file"$destinationPath"})
}

if($dbName&&$dbNamene''){
push(@args,qq{"$dbName"})
}

return@args
}

www.codeproject.com/Tips/308309/How-to-backup-multiple-databases-using-Perl?display=Print

5/8

02/06/14

How to backup multiple databases using Perl - CodeProject

#
#Returnsareadytoexecutecommandline
#
subcreateCommandLine{
my($arr)=@_
returnjoin("",@$arr)
}

main()

Parameters
Ichosethoseoptionsbecausetheyare"generic"andalmosteverydatabasesupportsthemYoucould
easilymodifythescripttoprovidespecialfeatures.
Thescriptcanbecalledfromacommandlineandreceivesthefollowingparameters:
1. utility:Absolutepathtothebackuputility(osql,exp,mysqldumporpgdump).
2. engine:Providethedatabaseengineyouwanttouse(mysql,sqlserver,oracleorpostgres)
3. host:Databaseservername.
4. port:Databaseserverport.
5. dbname:Nameofthedatabaseyouwanttobackup.
6. user:Databaseuser.
7. password:User'spassword.
8. dir:Placewhereyouwanttostorethebackupfileexample:"D:\backup"

UsingthescriptfromC#
classBackUp
{
publicBackUp(){}

publicvoidCreateBackup(stringscriptLocation,stringargs)
{
try
{
System.Diagnostics.ProcessStartInfop=new
System.Diagnostics.ProcessStartInfo(scriptLocation)
p.Arguments=args
System.Diagnostics.Processproc=newSystem.Diagnostics.Process()
proc.StartInfo=p
proc.Start()
proc.WaitForExit()
}
catch(Exceptione)
{
//handlethepossibleexceptionshere
}
}
}

www.codeproject.com/Tips/308309/How-to-backup-multiple-databases-using-Perl?display=Print

6/8

02/06/14

How to backup multiple databases using Perl - CodeProject

Usingtheclass:
//options
stringpath=Directory.GetCurrentDirectory()+"\\backup.pl"
stringutility=@"""C:\ProgramFiles\PostgreSQL\9.0\bin\pg_dump.exe"""
stringdbEngine="postgres"
stringhost="localhost"
intport=5432
stringdbName="Test"
stringdestinationPath=@"""D:\backup"""
stringuser="postgres"
stringpassword="12345"

//createtheargsstring
StringBuilderoptions=newStringBuilder()
options.Append("utility=").Append(utility).Append("")
options.Append("engine=").Append(dbEngine).Append("")
options.Append("host=").Append(host).Append("")
options.Append("port=").Append(port).Append("")
options.Append("dbname=").Append(dbName).Append("")
options.Append("user=").Append(user).Append("")
options.Append("password=").Append(password).Append("")
options.Append("dir=").Append(destinationPath).Append("")

//Instancetheclasswecreatedbefore
BackUpoBackUp=newBackUp()
oBackUp.CreateBackup(path,options.ToString())

Conclusion:
Perlisapowerfullanguagethatallowsustocreategreatthingsfastandeasy,anditcanruninthemost
popularoperatingsystems.

License
Thisarticle,alongwithanyassociatedsourcecodeandfiles,islicensedunderTheCodeProjectOpen
License(CPOL)

AbouttheAuthor

www.codeproject.com/Tips/308309/How-to-backup-multiple-databases-using-Perl?display=Print

7/8

02/06/14

How to backup multiple databases using Perl - CodeProject

CarlosLuis
SoftwareDeveloperAvantica
Technologies
CostaRica

NoBiographyprovided
Followon

Twitter

CommentsandDiscussions
0messageshavebeenpostedforthisarticleVisithttp://www.codeproject.com/Tips/308309/Howto
backupmultipledatabasesusingPerltopostandviewcommentsonthisarticle,orclickheretogeta
printviewwithmessages.
Permalink|Advertise|Privacy|Mobile
Web03|2.8.140526.1|LastUpdated7Jan2012

ArticleCopyright2012byCarlosLuis
EverythingelseCopyrightCodeProject,19992014
TermsofService

www.codeproject.com/Tips/308309/How-to-backup-multiple-databases-using-Perl?display=Print

8/8

Potrebbero piacerti anche