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();
}
}
