package mysqlstu
import java.sql.Connection
class MysqlDemo {
var driver = "com.mysql.cj.jdbc.Driver"
var url = "jdbc:mysql://192.168.91.130:3306/exam"
var user = "root"
var password = "root"
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 {
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: Connection = demo.conn
// demo.selectStudent
// val i: Int = demo.insertStudent
val i2: Int = demo.insertStudent("bigdata", 2, "女", "15853553511", "bigdata.com", 4)
println(i2)
// demo.selectStudent
// println(connection)
// demo.close(connection)
}
}
package mysqlstu
import java.sql.{Connection, DriverManager, PreparedStatement, ResultSet}
import java.util._
object MysqlUtil {
implicit class MysqlOp(obj: MysqlDemo) {
private var connection:Connection= _
def conn(): Connection = {
Class.forName(obj.driver)
val connection: Connection = DriverManager.getConnection(obj.url, obj.user, obj.password)
connection
}
def close(conn: Connection): Unit = {
if (conn != null) {
conn.close()
}
}
def insertStudent: Int = {
val insertSqlStr = "insert into student(name, age, gender, telephone, email, classid)" +
" values ('kb21',6,'男','15895746755','kb21@com',1)"
val i: Int = conn().createStatement.executeUpdate(insertSqlStr)
i
}
def insertStudent(name: String, age: Int, gender: String, telephone: String, email: String, classid: Int): Int = {
val insertSqlStr = "insert into student(name,age,gender,telephone,email,classid) values(?,?,?,?,?,?)"
val preStmt: PreparedStatement = conn().prepareStatement(insertSqlStr)
preStmt.setString(1, name)
preStmt.setInt(2, age)
preStmt.setString(3, gender)
preStmt.setString(4, telephone)
preStmt.setString(5, email)
preStmt.setInt(6, classid)
val i: Int =preStmt.executeUpdate()
i
}
def selectStudent():Unit={
val selectStr ="select id,name,age,gender,telephone,email,classid from Student"
val rs: ResultSet = conn().createStatement().executeQuery(selectStr)
println("学号\t姓名\t年龄\t性别\t电话\t邮箱\t学号\t")
while (rs.next()){
val id: Int = rs.getInt("id")
val name: String = rs.getString("name")
val age: Int = rs.getInt("age")
val gender: String = rs.getString("gender")
val telephone: String = rs.getString("telephone")
val email: String = rs.getString("email")
val classid: Int = rs.getInt("classid")
println(id+"\t"+name+"\t"+age+"\t"+gender+"\t"+telephone+"\t"+email+"\t"+classid+"\t")
}
}
}
}