package com.ruoze
import scalikejdbc._
import scalikejdbc.config._
object ScalalikeJdbc{
def main(args:Array[String]):Unit = {
//默认加载db.default.*配置信息
DBs.setupAll()
1.通过scalikejdbc查询user表所有的数据,封装进对象中
val memberIds:List[User] = DB readOnly { implicit session =>
sql"select * from user".map(rs => User(rs.int("id"), rs.string("name"), rs.int("age"))).list.apply()
}
println(memberIds)
打印的结果:List(User(1,tom,20), User(2,merry,20), User(3,mike,20), User(4,jeff,21), User(5,ff,22), User(6,ddd,23))
2.插入一条数据 插入成功返回1
val id = DB.localTx { implicit session =>
sql"INSERT INTO user(id, name, age) VALUES (?,?,?)".bind(2, "merry", 20).update().apply()
}
println(id)
3.插入多条数据
val users:List[User]= List(
User(4,"jeff",21),
User(5,"ff",22),
User(6,"ddd",23)
)
val id = DB.localTx { implicit session =>
for(x
sql"INSERT INTO user(id, name, age) VALUES (?,?,?)".bind(x.id, x.name, x.age).update().apply()
}
}
4.插入数据 使用自动提交
val id = DB.autoCommit { implicit session =>
sql"INSERT INTO user(id, name, age) VALUES (?,?,?)".bind(7, "merry", 20).update().apply()
}
println(id)
5.修改数据 将id=1的数据的age加10
val update = DB.autoCommit { implicit session =>
SQL("update user set age = age + 10 where id = ?").bind( "1").update().apply()
}
6、一次执行多条SQL,为了保证插入数据的幂等性
val id = DB.localTx { implicit session =>
sql"delete from hlwtest.result where count=?".bind(100).update().apply()
sql"insert into hlwtest.result(city_name,area,product_name,count) values(?,?,?,?)".bind("2", "2","2",200).update().apply()
}
println(id)
DBs.closeAll()
}
//用户实体:
case class User(id:Int,name:String,age:Int)
}