scala通过JDBC方式操作mysql (需要加载 mysql-connector-java 驱动)
maven依赖:
<dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.45</version></dependency>
一、scala连接mysql(jdbc方式)
import java.sql.{ Connection, DriverManager }object JBJDBC extends App {// 访问本地MySQL服务器,通过3306端口访问mysql数据库val url = "jdbc:mysql://localhost:3306/datassets_4300?useUnicode=true&characterEncoding=utf-8&useSSL=false"//驱动名称val driver = "com.mysql.jdbc.Driver"//用户名val username = "root"//密码val password = "123456"//初始化数据连接var connection: Connection = _try {//注册DriverClass.forName(driver)//得到连接connection = DriverManager.getConnection(url, username, password)val statement = connection.createStatement}}
}
前提:在我本地有一个Persion表,包括id和name两个字段
二、查询操作
通过connection.createStatement
进行数据的查询操作
val statement = connection.createStatement//执行查询语句,并返回结果val rs = statement.executeQuery("SELECT id,name FROM persons")//打印返回结果while (rs.next) {val id = rs.getString("id")val name = rs.getString("name")// println(name+"\t"+num)println("id = %s ,name = %s".format(id, name))}println("查询数据完成!")
三、增删改
val statement = connection.createStatement//执行查询语句,并返回结果val rs = statement.executeUpdate("SQL语句")