build.sbt:
import sbt._ import Process._ import Keys._ EclipseKeys.createSrc := EclipseCreateSrc.Default + EclipseCreateSrc.Resource lazy val commonSettings = Seq( name := "ScalaLearning", version := "1.0", scalaVersion := "2.10.6" ) lazy val root = (project in file(".")). settings(commonSettings: _*). settings( libraryDependencies ++= Seq( "org.scalikejdbc" %% "scalikejdbc" % "3.0.0", "mysql" % "mysql-connector-java" % "5.1.40", "ch.qos.logback" % "logback-classic" % "1.2.3", "org.scalariform" %% "scalariform" % "0.1.8" ) )
import scalikejdbc._ object SimpleDemo { def main(args: Array[String]): Unit = { Class.forName("com.mysql.jdbc.Driver") val url = "jdbc:mysql://192.168.1.151:3306/scalalearning?useUnicode=true&characterEncoding=UTF8" val userName = "root" val password = "12345" val settings = ConnectionPoolSettings( initialSize = 5, maxSize = 20, connectionTimeoutMillis = 3000L, validationQuery = "select 1 from dual") ConnectionPool.singleton(url, userName, password, settings) case class User(id: Int, name: String, age: Int) val allColumns = (rs: WrappedResultSet) => User( id = rs.int("id"), name = rs.string("name"), age = rs.int("age")) val users: List[User] = DB readOnly { implicit session => SQL("select * from user limit 10").map(allColumns).list.apply() } for(user <- users) { println(user.id + "," + user.name + "," + user.age) } } }
运行结果:
[SQL Execution] select * from user limit 10; (2 ms) [Stack Trace] ... com.citi.scalikejdbc.SimpleDemo$$anonfun$2.apply(SimpleDemo.scala:29) com.citi.scalikejdbc.SimpleDemo$$anonfun$2.apply(SimpleDemo.scala:28) scalikejdbc.DBConnection$class.readOnly(DBConnection.scala:202) scalikejdbc.DB.readOnly(DB.scala:60) scalikejdbc.DB$$anonfun$readOnly$1.apply(DB.scala:175) scalikejdbc.DB$$anonfun$readOnly$1.apply(DB.scala:174) scalikejdbc.LoanPattern$class.using(LoanPattern.scala:18) scalikejdbc.DB$.using(DB.scala:140) scalikejdbc.DB$.readOnly(DB.scala:174) com.citi.scalikejdbc.SimpleDemo$.main(SimpleDemo.scala:28) com.citi.scalikejdbc.SimpleDemo.main(SimpleDemo.scala) ... 1,sky,20 2,bill,30
时间: 2024-10-30 07:49:08