Scala 之 使用JDBC 操作 mysql

来源:互联网 发布:eclipse for linux汉化 编辑:程序博客网 时间:2024/05/01 14:44

zhuanzi :http://blog.csdn.net/u013041398/article/details/50968602

本文使用java JDBC连接,能够很好的解决scala与数据库连接的问题。本文使用的数据库为Mysql,scala 版本为2.10.4 。
  • 1
  • 2

1)修改built.sbt文件
在使用scala连接数据库之前,需要java JDBC driver加载到scala下面去,也就是在.sbt中添加相关的依赖包,需要添加的内容可以从mvnrepositoryhttp://mvnrepository.com/ 中获取,在搜索框中输入mysql就能弹出所需要的connector
这里写图片描述
本文使用的是sbt,因此使用libraryDependencies += “mysql” % “mysql-connector-java” % “5.1.38”句法,直接复制粘贴到built.sbt中即可。
2)scala 代码

  import java.sql.{Connection, DriverManager, ResultSet};  // Change to Your Database Config  val conn_str = "jdbc:mysql://localhost:3306/DBNAME?user=DBUSER&password=DBPWD"  // Load the driver  classOf[com.mysql.jdbc.Driver]  // Setup the connection  val conn = DriverManager.getConnection(conn_str)  try {      // Configure to be Read Only      val statement = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY)      // Execute Query      val rs = statement.executeQuery("SELECT quote FROM quotes LIMIT 5")      // Iterate Over ResultSet      while (rs.next) {          println(rs.getString("quote"))      }  } catch{    case e:Exception =>e.printStackTrace}  finally {      conn.close  }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

下面是使用jdbc和scala向数据库中插入数据的代码

  // create database connection  val dbc = "jdbc:mysql://localhost:3306/DBNAME?user=DBUSER&password=DBPWD"  classOf[com.mysql.jdbc.Driver]  val conn = DriverManager.getConnection(dbc)  val statement = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE)  // do database insert  try {    val prep = conn.prepareStatement("INSERT INTO quotes (quote, author) VALUES (?, ?) ")    prep.setString(1, "Nothing great was ever achieved without enthusiasm.")    prep.setString(2, "Ralph Waldo Emerson")    prep.executeUpdate  } catch{    case e:Exception =>e.printStackTrace}  finally {    conn.close  }

原创粉丝点击