pom.xml
<dependency>
<groupId>org.scalikejdbc</groupId>
<artifactId>scalikejdbc_2.11</artifactId>
<version>2.5.0</version>
</dependency>
<!-- scalikejdbc-config_2.11 -->
<dependency>
<groupId>org.scalikejdbc</groupId>
<artifactId>scalikejdbc-config_2.11</artifactId>
<version>2.5.0</version>
</dependency>
db.default.driver="com.mysql.jdbc.Driver"
db.default.url="jdbc:mysql://local:3306/bigdata?characterEncoding=utf8&useSSL=false"
db.default.user="root"
db.default.password="root"
import scalikejdbc._
import scalikejdbc.config.{DBs, DBsWithEnv}
object ScalajdbcDemo {
def main(args: Array[String]): Unit = {
//一行代码即可加载配置文件与建立连接池
DBs.setupAll()
//DBsWithEnv("development").setupAll()
val resData = (rs:WrappedResultSet)=>({
val str = rs.string("pro")
val i = rs.int("count")
Pro(str, i)
})
var offsets: List[Pro] =DB.readOnly(implicit it => {
SQL("select * from province").map(resData).list().apply()
})
offsets.foreach(println(_))
//带参查询
var offsets1: List[Pro] =DB.readOnly(implicit it => {
SQL("select * from province where count > ?").bind(2321).map(resData).list().apply()
})
offsets1.foreach(println(_))
//带多参查询
println("*2*")
var offsets2: List[Pro] = DB.readOnly(implicit it => {
SQL("select * from province where count > ? and count < ?").bind(321,3210).map(resData).list().apply()
})
offsets.foreach(println(_))
println("*3*")
//小写sql
var offsets3: List[Pro] = DB.readOnly(implicit it => {
sql"select * from province where count > ? and count < ?".bind(321,3210).map(resData).list().apply()
})
offsets3.foreach(println(_))
//插入数据
//插入数据
val sql = "insert into province values(?,?)"
//事务控制translation
val l = DB.localTx(implicit session => {
SQL(sql).bind("scalikejdbc", "9987").update().apply()
SQL(sql).bind("scalikejdbc01", "9987").update().apply()
})
println(l)
//不带事务控制,自动提交
DB.autoCommit(implicit session => {
SQL(sql).bind("scalikejdbc", "9987").update().apply()
SQL(sql).bind("scalikejdbc01", "9987").update().apply()
})
DBs.close()
}
}
case class Pro(pro:String,count:Int)
db.default.driver="com.mysql.jdbc.Driver"
db.default.url="jdbc:mysql://master:3306/bigdata?characterEncoding=utf8&useSSL=false"
db.default.user="root"
db.default.password="root"
development.db.default.driver="com.mysql.jdbc.Driver"
development.db.default.url="jdbc:mysql://master:3306/bigdata?characterEncoding=utf8&useSSL=false"
development.db.default.user="root"
development.db.default.password="root"
使用
DBsWithEnv("development").setupAll()
替代
DBs.setupAll()