Now I use gradle as my build tool. One of my tasks needs to access to a mysql database. Following is my gradle script:
import groovy.sql.Sql
buildscript {
The following snippet works well for connecting and querying database in Microsoft SQL SERVER. Please note that Microsoft does not make jar file 'sqljdbc42.jar'(which is jdbc driver) available on any online repo like MavenCentral(). Therefore, you would need to download this jar from Microsoft's website and save in project workspace directory. Download 'sqljdbc_4.2.6420.100_enu.exe'
Unzip the downloaded file and go to Microsoft JDBC Driver 4.2 for SQL Server-->sqljdbc_4.2-->enu. Here you will see the file sqljdbc42.jar. Copy the file into project workspace. I copied into dir name 'lib'.
repositories {
flatDir name: 'localRepository', dirs: 'lib'
}
configurations {
driver
}
dependencies {
driver group: 'sql', name: 'sqljdbc42', version:''
}
URLClassLoader loader = GroovyObject.class.classLoader
configurations.driver.each { File file ->
loader.addURL(file.toURL())
}
task connectToCoreDb << {
def props = [user: 'sa', password: 'shock', allowMultiQueries: 'true'] as Properties
def connectionUrl = "jdbc:sqlserver://cpt-op-01-db1:1433;databaseName=buds"
def driver = 'com.microsoft.sqlserver.jdbc.SQLServerDriver'
def sql = Sql.newInstance(connectionUrl, props, driver)
sql.eachRow('SELECT name, alias, expiry_date FROM [buds].[dbo].[obj_keystore] ) { row ->
println "$row.name $row.alias $row.expiry_date"
}
logger.info "Closing connection..."
sql.close()
}