ScalikeJDBC配置和简单使用

3 篇文章 0 订阅
官网地址:http://scalikejdbc.org/

参考官网:
在这里插入图片描述
添加maven依赖:

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.28</version>
</dependency>
<dependency>
	<groupId>org.scalikejdbc</groupId>
	<!-- 此处版本号config_2.11一定要和代码中编译scala的版本号一致 -->
	<artifactId>scalikejdbc-config_2.11</artifactId>
	<version>2.5.2</version>
</dependency>

在项目中的 src/main/resources/ 目录下创建文件 application.conf,拷贝如下代码到文件中:

# JDBC settings
db.default.driver="com.mysql.jdbc.Driver"
db.default.url="jdbc:mysql://master:3306/test_db"   //填写自己的数据库地址
db.default.user="root"         // 用户名
db.default.password="123456"   // 密码
# Connection Pool settings
db.default.poolInitialSize=10
db.default.poolMaxSize=20
db.default.connectionTimeoutMillis=1000

示例代码:

import scalikejdbc.{DB, SQL}
import scalikejdbc.config.DBs

object ScalikeJDBCApp {

  def insert(): Unit = {
    DB.autoCommit({
      implicit session => {
        SQL("insert into offset_table (topic, groupid, partitions, offset) values(?,?,?,?)")
          .bind("ts", "group", 3, 8)
          .update().apply()
      }
    })
  }

  def update(): Unit = {
    DB.autoCommit({
      implicit session => {
        SQL("update offset_table set offset=? where topic=? and groupid=? and partitions=?")
          .bind(18, "ts", "group", 3)
          .update().apply()
      }
    })
  }

  def query(): Unit = {
    val offsets = DB.readOnly({
      implicit session => {
        SQL("SELECT * FROM offset_table").map(rs => {
          Offset(
            rs.string("topic"),
            rs.string("groupid"),
            rs.int("partitions"),
            rs.long("offset")
          )
        }).list().apply()
      }
    })
    offsets.foreach(println)
  }

  def delete(): Unit = {
    DB.autoCommit({
      implicit session => {
        SQL("delete from offset_table  where partitions=?")
          .bind(3)
          .update().apply()
      }
    })
  }

  def transaction(): Unit = {
    DB.localTx({
      implicit session => {
        SQL("delete from offset_table  where partitions=?")
          .bind(2)
          .update().apply()
        //1/0
        SQL("delete from offset_table  where partitions=?")
          .bind(1)
          .update().apply()
      }
    })
  }

  def main(args: Array[String]): Unit = {
    DBs.setupAll() // 解析配置文件
    insert()	// 插入
    update()	// 更新
    query()		// 查询
    delete()	// 删除
    transaction()// 事务
  }
}

case class Offset(topic: String, groupId: String, partitionId: Int, offset: Long)
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值