main.resources.application.conf
db.test.driver="com.mysql.jdbc.Driver"
db.test.url="jdbc:mysql://192.168.75.245:3306/test?useSSL=false&characterEncoding=utf-8"
db.test.username="root"
db.test.password="Fang@123"
代码
package cn.kgc.scalajdbc.jdbc
import scalikejdbc.{NamedDB, SQL}
import scalikejdbc.config.DBs
object JdbcTest {
def main(args: Array[String]): Unit = {
//加载配置信息 : 自动解析 *.conf 下 db.db_shop12._的所有参数
val db:Symbol = Symbol.apply("test")
DBs.setup(db)
//创建增删改查的操作方法
//readonly : 查询
//autocommit : 非事务增删改
//localTx : 事务操作
def select(where:String="")={
val builder = new StringBuilder("select user_name,user_phone,user_pid from user_info")
if(where.trim.length>0){
builder.append(where)
}
//NameDB(db) 负责连接池创建
NamedDB(db).readOnly{
//sql(...) 解析数据语句
//bind(...)赋给sql语句中的参数?传值
//map() 执行查询操作并逐行处理
//list() 将Map()的结果以列表返回
//apply() 提取执行结果
implicit session => SQL(builder.toString).map(
//查询sql执行完毕后,逐行row提取,x就是数据表中的一行记录
row=>(
row.string("user_name"),
row.string("user_phone"),
row.string("user_pid")
)
).list().apply()
}
}
//批量插入 localTx: 事务操作
def batchInsert(arr:Array[(Int,String,Int,String,String,String,Int)])={
//负责连接池创建
NamedDB(db).localTx{
implicit session=>{
var affectedRows = 0
arr.foreach(x=>{
//sql(...) 解析数据语句
//bind(...)赋给sql语句中的参数?传值
//update() 执行增删改操作
//apply() 提取执行结果
affectedRows += SQL("insert into studentinfo(stuId,stuName,stuAge,stuGender,mobile,tuition,fkClassId) values(?,?,?,?,?,?,?)")
.bind(x._1,x._2,x._3,x._4,x._5,x._6,x._7).update().apply()
//affectedRows += SQL("insert into sqp_incr_time(incrName) values(?)").bind(x).update().apply()
})
affectedRows
}
}
}
//autocommit :非事务增删改
//单条记录新增
//批量修改
def update(x:(String,Int,String,String,String,Int,Int))={
//负责连接池创建
NamedDB(db).autoCommit{
implicit session=>{
var affectedRows:Int = 0
//sql(...) 解析数据语句
//bind(...)赋给sql语句中的参数?传值
//update() 执行增删改操作
//apply() 提取执行结果
affectedRows += SQL("update studentinfo set stuName=?,stuAge=?,stuGender=?,mobile=?,tuition=?,fkClassId=? where stuId=?")
.bind(x._1,x._2,x._3,x._4,x._5,x._6,x._7).update().apply()
//affectedRows += SQL("insert into sqp_incr_time(incrName) values(?)").bind(x).update().apply()
affectedRows
}
}
}
//删除
def delete(x:Int)={
//负责连接池创建
NamedDB(db).autoCommit{
implicit session=>{
//sql(...) 解析数据语句
//bind(...)赋给sql语句中的参数?传值
//update() 执行增删改操作
//apply() 提取执行结果
SQL("delete from studentinfo where stuId=?")
.bind(x).update().apply()
//affectedRows += SQL("insert into sqp_incr_time(incrName) values(?)").bind(x).update().apply()
}
}
}
//select().foreach(println)
//println(batchInsert(Array((52,"任志杰1",18,"男","13327791024","23345",1),(53,"任志杰2",18,"男","13327791036","23325",2))))
//println(batchInsert(Array((54,"任志杰3",18,"男","13327791345","23125",1))))
//println(update("任志杰4",18,"男","13327791345","23125",1,54))
//println(delete(52))
//println(batchInsert(Array("abc","def")))
}
}