Skip to content

Instantly share code, notes, and snippets.

@AGhost-7
Last active August 29, 2015 14:15
Show Gist options
  • Save AGhost-7/9d51a53ae6f7b3e8a9f2 to your computer and use it in GitHub Desktop.
Save AGhost-7/9d51a53ae6f7b3e8a9f2 to your computer and use it in GitHub Desktop.
SqlConnection.scala
import java.sql.{Connection, DriverManager}
import scala.util.Try
import java.net.{URISyntaxException, URI}
/** Object abstracts away some of the connection sheneanigans you need to do
* if you're trying to use JDBC. This is nice if you're just trying to make
* something of very simple with anorm (i.e., without Play! framework).
*/
object SqlConnection {
private val driverNames =
Map("postgresql" -> "org.postgresql.Driver",
"mysql" -> "com.mysql.jdbc.Driver")
private def findDriver(uri: String): String = {
val reg = """^(jdbc:)(.+)(:\/\/.+)""".r
val mOpt = reg.findFirstMatchIn(uri)
if(!mOpt.isDefined){
throw new URISyntaxException(uri, "JDBC uri not valid. Please enter " +
"a driver name instead.");
}
val dbName = mOpt.get.group(2)
val driverNameOpt = driverNames.get(dbName)
if(!driverNameOpt.isDefined){
throw new RuntimeException(s"Database $dbName is not automatically handled. " +
"You must manually enter the driver name.")
}
driverNameOpt.get
}
def defaultUri(baseUri: String): String =
if(!baseUri.contains("useOldAliasMetadataBehavior"))
if(baseUri.contains("?"))
baseUri + "&useOldAliasMetadataBehavior=true"
else
baseUri + "?useOldAliasMetadataBehavior=true"
else
baseUri
def apply(uri: String,
driver: Option[String] = None)
(func: Connection => Unit) {
val driverStr = driver.getOrElse { findDriver(uri) }
Class.forName(driverStr)
val uriDefault = defaultUri(uri)
val con = DriverManager.getConnection(uriDefault)
try { func(con) }
finally { con.close() }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment