scala快速⼊门开发四(连接mysql增删改查)scala 可以与Java⼀起连接mysql 操作数据库
⾸先引⼊mysql 的jar包
⽅式⼀使⽤scala 中的api 进⾏插⼊操作
package org.zw.sql
import java.sql.{ResultSet, DriverManager}mysql下载jar包
import scala.util.parsing.json.{JSONFormat, JSONObject, JSONArray, JSON}
object ScalaMysql {
def main(args: Array[String]) {
// create database connection
val dbc = "jdbc:mysql://localhost:3306/test?user=root&password=root"
sql.jdbc.Driver]
val conn = Connection(dbc)
val driver = "sql.jdbc.Driver"
val url = "jdbc:mysql://localhost:3306/test"
val username = "root"
val password = "root"
// do database insert
try {
Class.forName(driver)
val connection = Connection(url, username, password)
val prep = conn.prepareStatement("INSERT INTO blog (title, body) VALUES (?, ?) ")
prep.setString(1, "Nothing great was ever achieved without enthusiasm.")
prep.setString(2, "Ralph Waldo Emerson")
}
finally {
conn.close
}
}
}
⽅式⼆、使⽤Java  API ⽄⾏数据库数据查询
package org.zw.sql
import java.sql.DriverManager
import java.sql.Connection
object ScalaMysql2 {
def main(args: Array[String]) {
// connect to the database named "mysql" on the localhost
val driver = "sql.jdbc.Driver"
val url = "jdbc:mysql://localhost/test"
val username = "root"
val password = "root"
var connection:Connection = null
try {
Class.forName(driver)
connection = Connection(url, username, password)
val statement = ateStatement()
val resultSet = uteQuery("select * from blog")
while ( () ) {
val name = String("title")
val password = String("body")
println("name, password = " + name + ", " + password)
}
} catch {
case e => e.printStackTrace
//case _: Throwable => println("ERROR")
}
connection.close()
}
}
其实⼤部分与Java 的jdbc 是差不多的

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。