class JDBC{
fun connectMySql(){
//1. 加载驱动
val forName = Class.forName("com.mysql.jdbc.Driver")
//2. 获取连接
val jdbcUrl = "jdbc:mysql://127.0.0.1:3306/test_db"
val jdbcUrlUTC = "jdbc:mysql://127.0.0.1:3306/test_db?serverTimezone=UTC&characterEncoding=utf-8"
/**
* 如果出现如下错误则采用 ${jdbcUrlUTC}, 否者用 ${jdbcUrl} 即可
* com.mysql.cj.exceptions.InvalidConnectionAttributeException:
* The server time zone value 'Öйú±ê׼ʱ¼ä' is unrecognized or represents more than one time zone.
* You must configure either the server or JDBC driver (via the serverTimezone configuration property)
* to use a more specifc time zone
*/
val conn = DriverManager.getConnection(jdbcUrlUTC, "root", "root")
//3. 使用 Connection 创建 Statement 对象
val statement = conn.createStatement()
//4. 执行 SQL
/**
* Staement 有三种可执行 SQL 语句的方法:
* 1. execute() 可执行任何 SQL 语句——返回一个 boolean
* 值若果执行后第一个结果是 ResultSet,则返回 true,否者返回false
* 2. executeQuery() 执行 select 语句 —— 返回查询到的结果集
* 3. executeUpdate() 用于执行 DML 语句——返回一个整数
* 代表被 SQL 语句影响的记录条数
*/
val resultSet = statement.executeQuery("select * from tablename")
val idIndex = resultSet.findColumn("id")
val contentIndex = resultSet.findColumn("content")
val date_timeIndex = resultSet.findColumn("date_time")
println("idIndex= $idIndex contentIndex= $contentIndex date_timeIndex= $date_timeIndex")
while(resultSet.next()){
println("id = ${resultSet.getInt(idIndex)}\t" +
"content = ${resultSet.getString(contentIndex)}\t" +
"date_time = ${resultSet.getDate(date_timeIndex)}")
}
}
}