scala 通过jdbc访问mysql

scala是jvm语言,运行在jvm之上

我们知道jdbc是java访问数据库的技术,那么scala能不能通过jdbc操作数据库呢,答案是可以的

 

部分代码如下:

1
2
3
4
5
6
7
8
9
10
  /**
    * 获取连接
    */
  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
  }

  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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();
  }
}

  

posted @   裸奔的太阳  阅读(1197)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示