Scala connecting to MySQL with JDBC

scala使用jdbc就像Java程序一样。同样,我们得先下载MySQL的JDBC driver,本例使用的是 mysql-connector-java-5.1.34.jar

如下是Scala 以JDBC方式连接MySQL数据库的小实例:

package tests
import java.sql.{Connection, DriverManager}
object ScalaMysqlInsert extends App {
  // Connect to the database
  val url = "jdbc:mysql://192.168.10.2:3306/csg"
  val driver = "com.mysql.jdbc.Driver"
  val username = "root"
  val password = "root"
  var connection: Connection = _

  try {
    Class.forName(driver)
    connection = DriverManager.getConnection(url, username, password)
    val statement = connection.createStatement
    
    val create_sql  = "create table csg.test(id Int,name varchar(50))"
    statement.executeUpdate(create_sql)
    println("创建数据表成功!!!")
    
    val insert_sql = "insert into csg.test(id, name) values(1,'abc'),(2,'def')"
    statement.executeUpdate(insert_sql)
    println("数据插入成功!!!
    
    val query_sql = "select id, name from csg.test"
    val result = statement.executeQuery(query_sql)
    while (result.next) {
      val id = result.getString("id")
      val name = result.getString("name")
      println("id = %s, name = %s".format(id, name))
    }
  } catch {
    case e:Exception => e.printStackTrace
  }
  connection.close
}

运行结果如下:

创建数据表成功!!!
数据插入成功!!
id = 1, name = abc
id = 2, name = def

Process finished with exit code 0


你可能感兴趣的:(scala)