标签:drive nbsp pom ble 右键 ike type enc end
scalikejdbc官网:http://scalikejdbc.org/
ScalikeJDBC是简洁数据库访问库。该库自然包装JDBC API。
需求:使用scalikejdbc3.3.2版本来操作MySQL数据库
1) 通过SQL准备一张表user,有id,name,age三个字段
2) 通过scalikejdbc往user表里添加10条记录
3) 通过scalikejdbc查询user表所有的数据
4) 通过scalikejdbc将id=8的数据的age做修改,加10
mysql> use ruoze_g6;
mysql> create table user( id int, name varchar(100), age int );
1)pom中需要**添加scalikejdbc的依赖**:?
<dependency>
<groupId>org.scalikejdbc</groupId>
<artifactId>scalikejdbc_2.11</artifactId>
<version>3.3.2</version>
</dependency>
<dependency>
<groupId>org.scalikejdbc</groupId>
<artifactId>scalikejdbc-config_2.11</artifactId>
<version>3.3.2</version>
</dependency>
2)配置
右键Directory,名称为resources:
修改级联驱动,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
原文地址:https://www.cnblogs.com/huomei/p/12103736.html