Java 链接MySQL数据库【JDBC】

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)}")
        }

    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值