scala通过JDBC方式操作mysql (需要加载 mysql-connector-java 驱动)
maven依赖:
代码语言:javascript复制 <dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.45</version>
</dependency>
一、scala连接mysql(jdbc方式)
代码语言:javascript复制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 {
//注册Driver
Class.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("查询数据完成!")
三、增删改
代码语言:javascript复制val statement = connection.createStatement
//执行查询语句,并返回结果
val rs = statement.executeUpdate("SQL语句")