时间:2021-07-01 10:21:17 帮助过:48人阅读
修改级联驱动,scala是Sources,resources是Resources配置文件目录:
创建配置文件,及文件内容:
db.default.driver="com.mysql.jdbc.Driver"
db.default.url="jdbc:mysql://hadoop001:3306/ruoze_g6"
db.default.user="root"
db.default.password="123456"
3)代码:
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 <- users){
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()
}DBs.closeAll()
}
//用户实体:
case class User(id:Int,name:String,age:Int)
}
【Scala】Scala使用scalikejdbc工具连接MySQL(推荐)
标签:drive nbsp pom ble 右键 ike type enc end