大数据开发语言Scala(四)——Scala连接MySQL

一、添加依赖

  1. 打开项目构建,添加选择Libiary

  1. new Library中选择java

  1. 选中相应的jar包

  1. 成功导入

二、连接数据库并实现增删改查

这里我们实现两个类,一个用于测试Demo,一个用于实现增删改查的方法Utils

demo类:

// 连接数据库
class MysqlDemo {
  var driver="com.mysql.cj.jdbc.Driver"
  var url="jdbc:mysql://192.168.153.134:3306/school"
  var user="root"
  var password="123123"

  def this(driver:String,url:String,user:String,pwd:String){
    this()
    this.driver = driver
    this.url = url
    this.user = user
    this.password = pwd
  }
}

object MysqlDemo{
  // apply构造方法
  def apply(): MysqlDemo = new MysqlDemo()
  def apply(driver: String, url:String,user: String, pwd: String): MysqlDemo
    = new MysqlDemo(driver,url, user, pwd)

  // 测试
  def main(args: Array[String]): Unit = {
    val demo = MysqlDemo()
    import MysqlUtil._
    val connection = demo.conn()    // conn为utils类中方法
    println(connection)

    println(demo.insertStudent)
    println(demo.insertStudent(14,"李四","2000-01-01","男"))
    demo.selectStudent
    demo.close(connection)

  }
}

Utils类:

package org.example.mysqlstu
import java.sql.{Connection, Driver, DriverManager}

object MysqlUtil {

  implicit class MysqlOp(obj:MysqlDemo){
    private var connection:Connection = _;

//     获取connection方法
    def conn():Connection={
      Class.forName(obj.driver)
      val connection:Connection = DriverManager.getConnection(obj.url,obj.user,obj.password)
      connection
    }

//    关闭conn
    def close(conn:Connection)={
      if(conn!=null){
        conn.close()
      }
      println("关闭。。。")
    }

//    插入语句
    def insertStudent: Int ={
      val insertSqlStr="insert into student(SID,Sname,Sage,Ssex) values(13,\"张三\",\"1999-09-09\",\"女\")"
      val i:Int = conn.createStatement.executeUpdate(insertSqlStr)
      i
    }

//    插入自定义数据
    def insertStudent(id:Int,name:String,age:String,sex:String):Int={
      val insertSqlStr="insert into student(SID,Sname,Sage,Ssex) values(?,?,?,?)"
      val preStmt = conn.prepareStatement(insertSqlStr)
      preStmt.setInt(1,id)
      preStmt.setString(2,name)
      preStmt.setString(3,age)
      preStmt.setString(4,sex)
      val i = preStmt.executeUpdate()
      i
    }

//    查询语句
    def selectStudent:Unit={
      val selectStr = "select SID,Sname,Sage,Ssex from student"
      val set = conn.createStatement().executeQuery(selectStr)
      while(set.next()){
        val id = set.getInt(1)
        val name = set.getString(2)
        val age = set.getString(3)
        val sex = set.getString(4)
        println(s"student{ ${id},${name},${age},${sex} }")
      }
    }
  }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值