Created
January 20, 2016 19:13
-
-
Save dyerrington/a0dfc409ca7de3fbe605 to your computer and use it in GitHub Desktop.
I know there are better ways to handle this problem explicitly but I do a lot of prototyping and it's helpful to have JDBC dynamically map to equivalent Scala types, so I read the docs about Java's java.sql.Types (https://docs.oracle.com/javase/6/docs/api/constant-values.html#java.sql.Types), and setup this basic JDBC sql type to Scala mapping m…
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def getJDBCResults(sql:String = "SHOW PROCESSLIST()") : List[Map[String,Any]] = { | |
// classOf[com.mysql.jdbc.Driver] | |
val conn = DriverManager.getConnection(s"${this.dsn}?user=${this.dbuser}&password=${this.dbpassword}") | |
try { | |
// Configure to be Read Only | |
val statement = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY) | |
val rs = statement.executeQuery(sql) | |
var results:List[Map[String,Any]] = List() | |
// Iterate Over ResultSet | |
while (rs.next) { | |
val metaData = rs.getMetaData() | |
var metaMap:Map[String, Any] = Map() | |
println(Types.VARCHAR) | |
for(index <- 1 to metaData.getColumnCount()) { | |
println(metaData.getColumnType(index)) | |
val attribute = metaData.getColumnLabel(index) | |
val colType = metaData.getColumnType(index) | |
colType match { | |
case Types.FLOAT | Types.REAL | Types.DOUBLE | Types.DECIMAL => { | |
println("get float") | |
metaMap += (attribute -> rs.getFloat(attribute)) | |
} | |
case Types.INTEGER | Types.BIGINT | Types.SMALLINT => { | |
println("getting int") | |
metaMap += (attribute -> rs.getInt(attribute)) | |
} | |
case _ => { | |
metaMap += (attribute -> rs.getString(attribute)) | |
} | |
} | |
} | |
// append results | |
results :+= metaMap | |
} | |
return results | |
} | |
finally { | |
conn.close | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment