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
}