你如何在Scala游戏之外使用Anorm?在Anorm文档中,它只是使用类似的东西:
DB.withConnection { implicit c =>
val result: Boolean = SQL("Select 1").execute()
}
DB
对象仅适用于Play。如何在不使用Play的情况下单独使用Anorm?
答案 0 :(得分:14)
不需要DB
对象(Play JDBC的一部分而不是Anorm)。 Anorm与您提供隐式的连接一样工作:
implicit val con: java.sql.Connection = ??? // whatever you want to resolve connection
SQL"SELECT * FROM Table".as(...)
您可以通过多种方式解析JDBC连接:基本DriverManager.getConnection
,JNDI,...
至于依赖性,可以很容易地在SBT中添加它:How to declare dependency on Play's Anorm for a standalone application?。
答案 1 :(得分:1)
你也可以按如下方式模拟数据库对象(虽然我没试过)
object DB {
def withConnection[A](block: Connection => A): A = {
val connection: Connection = ConnectionPool.borrow()
try {
block(connection)
} finally {
connection.close()
}
}
}
取自https://github.com/TimothyKlim/anorm-without-play/blob/master/src/main/scala/Main.scala
答案 2 :(得分:0)
在下面记录对我有用的代码:
要包含在build.sbt
中的依赖项中的条目:
// https://mvnrepository.com/artifact/org.playframework.anorm/anorm
libraryDependencies += "org.playframework.anorm" %% "anorm" % "2.6.7"
编写帮助程序类:
@Singleton
class DBUtils {
val schema = AppConfig.defaultSchema
def withDefaultConnection(sqlQuery: SqlQuery) = {
// could replace with DBCP, not got a chance yet
val conn = DriverManager.getConnection(AppConfig.dbUrl,AppConfig.dbUser, AppConfig.dbPassword)
val result = Try(sqlQuery.execute()(conn))
conn.close()
result
}
}
object DBUtils extends DBUtils
接下来,任何查询都可以使用withDefaultConnection
方法执行:
def saveReviews(listOfReviews: List[Review]):Try[Boolean]= {
val query = SQL(
s"""insert into aws.reviews
| ( reviewerId,
| asin,
| overall,
| summary,
| unixReviewTime,
| reviewTime
| )
|values ${listOfReviews.mkString(",")}""".stripMargin)
//println(query.toString())
DBUtils.withDefaultConnection(query)
}