一、添加依赖
打开项目构建,添加选择Libiary
new Library中选择java
选中相应的jar包
成功导入
二、连接数据库并实现增删改查
这里我们实现两个类,一个用于测试Demo,一个用于实现增删改查的方法Utils
demo类:
// 连接数据库
class MysqlDemo {
var driver="com.mysql.cj.jdbc.Driver"
var url="jdbc:mysql://192.168.153.134:3306/school"
var user="root"
var password="123123"
def this(driver:String,url:String,user:String,pwd:String){
this()
this.driver = driver
this.url = url
this.user = user
this.password = pwd
}
}
object MysqlDemo{
// apply构造方法
def apply(): MysqlDemo = new MysqlDemo()
def apply(driver: String, url:String,user: String, pwd: String): MysqlDemo
= new MysqlDemo(driver,url, user, pwd)
// 测试
def main(args: Array[String]): Unit = {
val demo = MysqlDemo()
import MysqlUtil._
val connection = demo.conn() // conn为utils类中方法
println(connection)
println(demo.insertStudent)
println(demo.insertStudent(14,"李四","2000-01-01","男"))
demo.selectStudent
demo.close(connection)
}
}
Utils类:
package org.example.mysqlstu
import java.sql.{Connection, Driver, DriverManager}
object MysqlUtil {
implicit class MysqlOp(obj:MysqlDemo){
private var connection:Connection = _;
// 获取connection方法
def conn():Connection={
Class.forName(obj.driver)
val connection:Connection = DriverManager.getConnection(obj.url,obj.user,obj.password)
connection
}
// 关闭conn
def close(conn:Connection)={
if(conn!=null){
conn.close()
}
println("关闭。。。")
}
// 插入语句
def insertStudent: Int ={
val insertSqlStr="insert into student(SID,Sname,Sage,Ssex) values(13,\"张三\",\"1999-09-09\",\"女\")"
val i:Int = conn.createStatement.executeUpdate(insertSqlStr)
i
}
// 插入自定义数据
def insertStudent(id:Int,name:String,age:String,sex:String):Int={
val insertSqlStr="insert into student(SID,Sname,Sage,Ssex) values(?,?,?,?)"
val preStmt = conn.prepareStatement(insertSqlStr)
preStmt.setInt(1,id)
preStmt.setString(2,name)
preStmt.setString(3,age)
preStmt.setString(4,sex)
val i = preStmt.executeUpdate()
i
}
// 查询语句
def selectStudent:Unit={
val selectStr = "select SID,Sname,Sage,Ssex from student"
val set = conn.createStatement().executeQuery(selectStr)
while(set.next()){
val id = set.getInt(1)
val name = set.getString(2)
val age = set.getString(3)
val sex = set.getString(4)
println(s"student{ ${id},${name},${age},${sex} }")
}
}
}
}