Scala 简易实现JDBC
实现方法和java类似,不考虑隐式的话,基本上和java没什么区别
package zb.kb11
import java.sql
import java.sql.DriverManager
class homework1{
private var driver="com.mysql.jdbc.Driver"
private var url="jdbc:mysql://192.168.146.222:3306"
private var user="root"
private var password="1"
private var connection:sql.Connection=_
def conn():sql.Connection={
Class.forName(driver)
connection=DriverManager.getConnection(url,user,password)
connection
}
def insert (id:Int,name:String,age:Int):Int={
var insertSql="insert into test.student(id,name,age) values(4,'zhaowu',22)"
val prep=conn().prepareStatement(insertSql)
prep.setInt(1,id)
prep.setString(2,name)
prep.setInt(3,age)
var i=prep.executeUpdate()
i
}
def select():Unit={
val selectSql="select * from test.student1"
val res=conn().createStatement().executeQuery(selectSql)
while(res.next()){
val id=res.getInt(1)
val name=res.getString(2)
val age=res.getInt(3)
println("学号:%d 姓名:%s 年龄:%d".format(id,name,age))
}
}
}
object homework1 {
def main(args: Array[String]): Unit = {
val aa=new homework1
aa.select()
}
}