• Scala 操作Mysql


    一、工具IDEA+MAVEN

    二、Pom文件添加依赖 
    1、更改成自己的scala版本

    <properties>
        <scala.version>2.11.8</scala.version>
      </properties>
    • 1
    • 2
    • 3

    2、添加驱动依赖

     <dependency>
          <groupId>mysql</groupId>
          <artifactId>mysql-connector-java</artifactId>
          <version>5.1.12</version>
        </dependency>
    • 1
    • 2
    • 3
    • 4
    • 5

    三、代码书写 
    1、DBUtils

    package com.encapsulation
    import java.sql
    import java.sql.{Connection, DriverManager}
    /**
      * Created by A chun on 2017/10/18.
      */
    object DBUtils {
      val IP = "127.0.0.1"
      val Port = "3306"
      val DBType = "mysql"
      val DBName = "scala"
      val username = "root"
      val password = "123456"
      val url = "jdbc:" + DBType + "://" + IP + ":" + Port + "/" + DBName
      classOf[com.mysql.jdbc.Driver]
    
      def getConnection(): Connection = {
        DriverManager.getConnection(url, username, password)
      }
      def close(conn: Connection): Unit = {
        try {
          if (!conn.isClosed() || conn != null) {
            conn.close()
          }
        }
        catch {
          case ex: Exception => {
            ex.printStackTrace()
          }
        }
      }
    }
    

    2、Operations

    package com.encapsulation
    import com.encapsulation.DBUtils.close
    
    import scala.collection.mutable
    import scala.collection.mutable.ArrayBuffer
    class Operations {
      case class User(id: String, name: String, age: Int)
      //insert
      def add(user: User): Boolean = {
        val conn = DBUtils.getConnection()
        try {
          val sql = new StringBuilder()
            .append("INSERT INTO user(id, name, age)")
            .append("     VALUES(?, ?, ?)")
          val pstm = conn.prepareStatement(sql.toString())
          pstm.setObject(1, user.id)
          pstm.setObject(2, user.name)
          pstm.setObject(3, user.age)
    
          pstm.executeUpdate() > 0
        }
        finally {
          conn.close()
        }
      }
      //delete
      def delete(id: String): Boolean = {
        val conn = DBUtils.getConnection()
        try {
          val sql = "DELETE FROM user WHERE id = ?"
          val pstm = conn.prepareStatement(sql)
          pstm.setObject(1, id)
          pstm.executeUpdate() > 0
        }
        finally {
          conn.close()
        }
      }
      //update
      def modify(user: User): Boolean = {
        val conn = DBUtils.getConnection()
        try {
          val sql = "UPDATE user SET age = ? WHERE id = ?"
          val pstm = conn.prepareStatement(sql)
          pstm.setObject(1, user.age)
          pstm.setObject(2, user.id)
    
          pstm.executeUpdate() > 0
        }
        finally {
          conn.close()
        }
      }
      //select
      def query(id: Int): ArrayBuffer[mutable.HashMap[String, Any]] = {
        val conn = DBUtils.getConnection()
        try {
          val sql = new StringBuilder()
            .append("SELECT name, age")
            .append("  FROM user")
            .append(" WHERE id >  ?")
          val pstm = conn.prepareStatement(sql.toString())
          pstm.setObject(1, id)
          val rs = pstm.executeQuery()
          val rsmd = rs.getMetaData()
          val size = rsmd.getColumnCount()
          val buffer = new ArrayBuffer[mutable.HashMap[String, Any]]()
          while (rs.next()) {
            val map = mutable.HashMap[String, Any]()
            for (i <- 1 to size) {
              map += (rsmd.getColumnLabel(i) -> rs.getString(i))
            }
            buffer += map
          }
    
          buffer
        }
        finally {
          conn.close()
        }
      }
    }
    

    3、MySQLOperations

    package com.encapsulation
    
    object MySQLOperations {
      def main(args: Array[String]): Unit = {
        val op = new Operations()
        val user = op.User("5", "Allen", 34)
        //Insert
        //println(op.add(user))
    
        //Delete
        println(op.delete("5"))
    
        //update
        //println(op.update(user))
      }
    }
  • 相关阅读:
    通过点击切换文本框内容的脚本示例
    使用脚本改变树控件的行为
    javascript动态创建radio button元素支持IE/Firefox
    轻量级的向导控件MultiView
    客户端脚本简单实现Repeater的无刷新分页
    在非web site项目中引用Membership
    逐步认识C#四种判断相等的方法
    C#获取csv文件内容对逗号和引号分隔的处理
    JavaScript之 值类型 和 引用类型 Better
    JS call apply bind 方法的区别 Better
  • 原文地址:https://www.cnblogs.com/kxgdby/p/7956601.html
Copyright © 2020-2023  润新知