您的位置:首页 > 数据库 > MySQL

scala 使用JDBC方式访问Mysql

2016-03-24 10:55 381 查看

scala 使用JDBC方式访问Mysql

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


1)修改built.sbt文件

在使用scala连接数据库之前,需要java JDBC driver加载到scala下面去,也就是在.sbt中添加相关的依赖包,需要添加的内容可以从mvnrepository http://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
}


下面是使用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
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: