Skip to content

Instantly share code, notes, and snippets.

@randrews
Created August 22, 2009 23:33
Show Gist options
  • Save randrews/173043 to your computer and use it in GitHub Desktop.
Save randrews/173043 to your computer and use it in GitHub Desktop.
importClass(Packages.java.sql.DriverManager);
importClass(Packages.java.sql.ResultSet);
// Let the classloader see it.
new Packages.com.mysql.jdbc.Driver();
var DB_BASE='kingdom';
var DB_USER='root';
var DB_PASS='';
var DB_HOST='localhost';
function dbConnection(mode){
mode=mode||'development';
var conn=DriverManager.
getConnection('jdbc:mysql://'+DB_HOST+'/'+DB_BASE+'_'+mode,
DB_USER,
DB_PASS);
return conn;
}
var CONN=dbConnection('development');
function dbQuery(str,updatable){
if(updatable){
return CONN.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE).executeQuery(str);
}else{
return CONN.createStatement().executeQuery(str);
}
}
function dbMap(str,fn){
var rs=dbQuery(str,true);
var a=[];
var thunk=dbBuildThunk(rs);
while(rs.next()){
a.push(fn(thunk));
if(updatedRow){
updatedRow=false;
rs.updateRow();
}
}
return a;
}
function dbBuildThunk(rs){
var meta=rs.getMetaData();
var cols={};
for(var k=1;k<=meta.getColumnCount();k++){
cols[meta.getColumnName(k)]=k;
}
var updatedRow=false;
return function(col,newVal){
if(typeof col === 'string'){
col=cols[col];
}
if(newVal===undefined){
return rs.getObject(col);
}else{
updatedRow=true;
rs.updateObject(col,newVal);
}
};
}
function dbInsert(table,populate){
var rs=dbQuery("select * from "+table+" where false",true);
rs.moveToInsertRow();
if(typeof populate === 'function'){
populate(dbBuildThunk(rs));
}
rs.insertRow();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment