//see: http://groovy.codehaus.org/Tutorial+6+-+Groovy+SQL
@Grapes(
@Grab(group='mysql', module='mysql-connector-java', version='5.1.26')
)
@GrabConfig(systemClassLoader=true)
import groovy.sql.Sql
String user = "root"
String pwd = "1234"
String fileTable = "mcScrap";
List fileCols = ['col1','test1col'];
def sql = Sql.newInstance("jdbc:mysql://localhost:3306/onix21", user, pwd, "com.mysql.jdbc.Driver")
println "Connected!\n"
println "Found $fileTable ?: " + !!(sql.rows("SHOW TABLES LIKE ${fileTable}").size())
String command = """
CREATE TABLE IF NOT EXISTS `$fileTable` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT ,
`${fileCols[0]}` VARCHAR(45) NULL ,
`${fileCols[1]}` VARCHAR(45) NULL ,
PRIMARY KEY (`id`) ,
UNIQUE INDEX `id_UNIQUE` (`id` ASC) );
"""
println command
println sql.execute(command)
command = "SELECT * FROM `$fileTable`"
println command
sql.eachRow(command) { println "$it.id -- ${it[fileCols[0]]} -- ${it[fileCols[1]]} --" }
println sql.execute("INSERT INTO `$fileTable` (${fileCols.join(',')}) VALUES (?,?);", ['1','1'])
command = "SELECT * FROM `$fileTable`"
println command
sql.eachRow(command) { println "$it.id -- ${it.col1} -- ${it.test1col} --" }
println sql.executeUpdate("UPDATE `$fileTable` SET ${fileCols[0]} = ? WHERE ${fileCols[1]}=1", [Math.random()])
List rows = []
sql.eachRow(command) { rows << (it.toRowResult() as HashMap) }
println "rows: " + rows.size()
println "type: " + rows[0].getClass().name
println "1st: " + rows[0]
println "all: " + rows
Friday, August 23, 2013
MySQL Connect and Query bootstrap
Monday, July 29, 2013
GroupBy and SubMap
int groups = 7
//divide list up into groups by % (their remainder)
Map a = (1..50).groupBy({ it % groups }) as TreeMap
assert a.keySet() == (0..<groups) as Set
assert a.keySet() == [0, 1, 2, 3, 4, 5, 6] as Set
//pull out specific keys (plus vals) from a Map
assert a.subMap(1) == [1:[1, 8, 15, 22, 29, 36, 43, 50]]
assert a.subMap([1,2]) == [1:[1, 8, 15, 22, 29, 36, 43, 50], 2:[2, 9, 16, 23, 30, 37, 44]]
assert a.subMap([1,2,99]) == [1:[1, 8, 15, 22, 29, 36, 43, 50], 2:[2, 9, 16, 23, 30, 37, 44], 99:null]
assert a.subMap([1,2,99]).findAll({k,v->!!v}) == [1:[1, 8, 15, 22, 29, 36, 43, 50], 2:[2, 9, 16, 23, 30, 37, 44]]
assert a.subMap((1..3)) == [1:[1, 8, 15, 22, 29, 36, 43, 50], 2:[2, 9, 16, 23, 30, 37, 44], 3:[3, 10, 17, 24, 31, 38, 45]]
Intersect Lists and Maps
List a = [1,2,3] List b = [2,3,4] assert [2,3] == a.intersect(b) assert [1,2,3,4] == (a + b).unique() assert [1] == a - b assert [4] == b - a Map c = [a:1, b:2, c:44] Map d = [b:2, c:3] assert [b:2] == c.intersect(d) assert [a:1, b:2, c:3] == c + d assert [a:1, b:2, c:44] == d + c assert [a:1, c:44] == c - d assert [c:3] == d - c
Wednesday, July 24, 2013
Random String generator
//see: http://groovyconsole.appspot.com/edit/1032002
String generateToken(Integer size = 16){
String availableChars = 'ABCDEFGHIJLMNOPQRSTUVXZYabcdefghijlmnopqrstuvxzy0123456789!@#$%*_'
Random generator = new Random()
String token = ""
size.times {
token += availableChars[generator.nextInt(availableChars.length() - 1)]
}
return token
}
generateToken()
generateToken(8)
Thursday, July 4, 2013
printf with Strings
//all formatting options: http://docs.oracle.com/javase/6/docs/api/java/util/Formatter.html#syntax
//test padding on both sides of "HI"//
(-8..8).each{ i ->
if (i == 0) i = '' // avoid illegal printf syntax
String f = "**%${i}s**"
print ((f + ' --> ').padRight(15)) // just for debugging
printf(f+'\n', "HI")
}
//Tic Tac Toe//
List field = [["","x","o"],["","x",""],["o","",""]]
field.eachWithIndex { line,index ->
if(index > 0) {
println "---+" * 2 + "---"
}
printf(" %-2s| %-2s| %-2s\n", line)
}
Monday, June 17, 2013
Gradle templates
// Generate a new Groovy Project Qwickly (tm) //
// source: https://github.com/townsfolk/gradle-templates
// in build.gradle file (in the project's root folder):
apply from: 'http://www.tellurianring.com/projects/gradle-plugins/gradle-templates/apply.groovy'
dependencies {
groovy localGroovy()
}
//then get a list of tasks:
>> gradle tasks
...
Template tasks
--------------
createGroovyClass - Creates a new Groovy class in the current project. **************
createGroovyProject - Creates a new Gradle Groovy project in a new directory named after your project.
createJavaClass - Creates a new Java class in the current project.
createJavaProject - Creates a new Gradle Java project in a new directory named after your project.
exportGroovyTemplates - Exports the default groovy template files into the current directory.
exportJavaTemplates - Exports the default java template files into the current directory.
initGroovyProject - Initializes a new Gradle Groovy project in the current directory. **************
initJavaProject - Initializes a new Gradle Java project in the current directory.
...
>> gradle initGroovyProject
>> gradle createGroovyClass
/**********************************************************/
//Here's a pretty useful project build.gradle:
apply plugin: 'groovy'
apply from: 'http://www.tellurianring.com/projects/gradle-plugins/gradle-templates/apply.groovy'
apply from: 'http://evgenyg.artifactoryonline.com/evgenyg/libs-releases-local/CodeNarc.gradle'
group = 'myapp1'
mainClassName = 'org.MyCompany.Main'
dependencies {
groovy localGroovy()
}
jar {
manifest {
attributes("Main-Class": mainClassName)
}
}
// uberjar adds in groovy jars to make this easy: "java -jar MyApp.jar"
task uberjar(type: Jar, dependsOn:[':compileJava', ':compileGroovy']) {
from files(sourceSets.main.output.classesDir)
from configurations.runtime.asFileTree.files.collect { zipTree(it) }
manifest {
attributes 'Main-Class': mainClassName
}
}
Script template
// this is just intended to give a little more OOP structure to a script.
// put most code inside of run(), plus class variables and methods.
class Script {
private String hello = "Hello"
public Script run(Map options = [:]) {
println "$hello ${options.name ?: 'World'}${shout(23)}"
return this // for method chaining
}
private String shout(int times = 1) {
return ('!' * times)
}
}
new Script()
.run()
.run([name:'Crazy4Groovy'])
println 'DONE'
Subscribe to:
Posts (Atom)