Skip to content

Instantly share code, notes, and snippets.

@quchie
Last active August 29, 2015 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save quchie/cd6b42178f97230216b4 to your computer and use it in GitHub Desktop.
Save quchie/cd6b42178f97230216b4 to your computer and use it in GitHub Desktop.
Transfer Data from Database to another database using groovy script.
--This is the Query for the Host DB
--TODO: Change This
SELECT * FROM TABLENAME
import groovy.sql.Sql
import java.sql.SQLException
/*
Purpose: transfer data from one database to another database.
==============================================
Database to Database transfer
==============================================
Tested on version Groovy 2.1.1
Get JAVA
===========
Get the suitable Java distribution from the http://java.sun.com website.
Run the installer.
Set the JAVA_HOME environment variables. On Windows, follow these steps:
Open the System control panel
Click the Advanced tab
Click the Environment Variables button
Add a new System variable with the name JAVA_HOME and the value of the directory Java was installed in (mine is C:\Program Files\Java\jdk1.5.0_04)
Add %JAVA_HOME%\bin to your system path
Get Groovy
===========
go to http://groovy.codehaus.org/Download
Download Windows-Installer: Binary Release
Say Yes to everything during wizard.
Make sure during installation, Set the GROOVYPATH into the environment
Get Any JDBC Driver
===============================
Download JDBC driver that you need.
To install, copy & paste the *.jar to installed Groovy lib directory:
eg: C:\Program Files (x86)\Groovy\Groovy-2.1.1\lib
*/
//========Do Not Change Start
Sql hostdb
Sql targetdb
int i = 0
String anim= "|/-\\"
//========Do Not Change End
try {
//TODO:Change: JDBC Connection String
hostdb = Sql.newInstance('jdbc:oracle:thin:@host:port:dbname', 'username', 'password', 'oracle.jdbc.OracleDriver')
targetdb = Sql.newInstance("jdbc:mysql://host:port/dbname", "username","password", "com.mysql.jdbc.Driver")
//TODO:Change:Get hostdb Queries in text file
String hostdb_query = new File('E:/SQL/SQL_QUERY_FOR_HOST.sql').text
hostdb.eachRow(hostdb_query){results ->
//TODO:Change: Insert Statement for targetdb Query
def transferResult = targetdb.execute "INSERT INTO targetdbTable values ($results.column1,$results.column2)"
//========Do Not Change Start
i = i +1
String data = "\r" + anim.charAt(i % anim.length()) + " " + i + " rows processed.";
System.out.write(data.getBytes());
}
if (transferResult){
println transferResult
}else {
println "Nothing Returned. A Sucess for Insert operation."
}
println("\nProcessing: Done! ")
}catch(SQLException e){
println "Error: "+e
println "SQL Error Code: "+e.getErrorCode()
println "SQL State: "+ e.getSQLState()
println "\nProcessing: Failed!"
}
//========Do Not Change End
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment