Scala的JDBC操作

scala对JDBC的操作与Java的类似,这里以连接mysql为例

  • 如果新建的的maven项目,直接在xml文件中配置以下代码即可,版本号可根据自己的mysql版本调整
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.38</version>
</dependency>
  • 若不是maven项目,则需要手动导入mysql的jar包
    File —> Project Structure —> Libraies
    找到自己jar存放位置,添加进入即可
    Scala的JDBC操作_第1张图片
  • 数据库准备
# 新建scalaDemo库
CREATE DATABASE scalaDemo;
# 使用这个库
USE scalaDemo;
# 创建student表
CREATE TABLE student (
 sid INT PRIMARY KEY AUTO_INCREMENT,
 sname VARCHAR(20),
 age INT
);
  • 具体操作
import java.sql.{Connection, DriverManager, PreparedStatement, ResultSet}

object scalaJDBC {
  private val Driver="com.mysql.jdbc.Driver"
  private val url = "jdbc:mysql://192.168.233.133:3306/scalademo"
  private val username = "root"
  private val password= "root"

  var conn:Connection = null
  var pst:PreparedStatement = null
  var rs:ResultSet = null

  def getConnection():Unit = {
    Class.forName(Driver);
    conn = DriverManager.getConnection(url,username,password)
  }

  // 增删改操作
  // 参数为需要执行的sql语句,obj参数数量不固定,按需传递
  def update(sql:String,obj:Any*):Int={
    // 创建连接
    getConnection()
    // 创建prepareStatement对象
    pst = conn.prepareStatement(sql)
    // 循环给赋值
    for(i <- 0 until obj.length){
      pst.setObject(i+1,obj(i))
    }
    val num = pst.executeUpdate()
    pst.close()
    conn.close()
    num
  }

  // 查询全部信息
  def select()={
    getConnection()
    val sql = "select sid,sname,age from student"
    pst = conn.prepareStatement(sql)
    rs = pst.executeQuery()
    while(rs.next()){
      val id  = rs.getInt("sid")
      val name = rs.getString("sname")
      val age = rs.getInt("age")
      println(id+" "+name+" "+age)
    }
    rs.close()
    pst.close()
    conn.close()
  }
  
  def main(args: Array[String]): Unit = {
    // 插入
    val sql = "insert into student(sname,age) values(?,?)"
    println(update(sql,"张三",25))
    // 删除
    val sql2 = "delete from student where sid = ?"
    println(update(sql2,2))
    // 修改
    val sql3 = "update student set sname=?,age=? where sid=?"
    println(update(sql3,"赵四",70,6))
    // 查询
    select()
  }
}

你可能感兴趣的:(Scala,jdbc,mysql,scala)