scala是jvm语言,运行在jvm之上
我们知道jdbc是java访问数据库的技术,那么scala能不能通过jdbc操作数据库呢,答案是可以的
部分代码如下:
/**
* 获取连接
*/
private def getJdbcConnection(): Connection = {
// classOf[com.mysql.jdbc.Driver]
Class.forName("com.mysql.jdbc.Driver").newInstance()
val jdbcUrl = "jdbc:mysql://localhost:3306xxxxx"
val conn = DriverManager.getConnection(jdbcUrl, "userName", "password")
conn
}
var ps: PreparedStatement = null
val sql = "insert into person(send_name, stock_code, stock_name, send_datetime, content, weibo_id) " +
"values(?,?,?,?,?,?)"
try {
ps = getJdbcConnection().prepareStatement(sql)
ps.setString(1, "11");
ps.setString(2, "22");
ps.setString(3, "33");
ps.setDate(4, null)
ps.setString(5, "55")
ps.setString(6, "66")
ps.executeUpdate()
} catch {
case t: Throwable => t.printStackTrace() // TODO: handle error
} finally {
if (ps != null) {
ps.close();
}
}