JDBC示例

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/mingyundezuoan/article/details/82319068

JDBC方式连接MySQL示例


准备

  • 建表
mysql> show databases ;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mybatis            |
| mysql              |
| performance_schema |
| test               |
+--------------------+
5 rows in set

mysql> use mybatis ;
Database changed
mysql> show tables ;
+-------------------+
| Tables_in_mybatis |
+-------------------+
| t_role            |
+-------------------+
1 row in set

mysql> desc t_role ;
+-----------+-------------+------+-----+---------+----------------+
| Field     | Type        | Null | Key | Default | Extra          |
+-----------+-------------+------+-----+---------+----------------+
| id        | int(10)     | NO   | PRI | NULL    | auto_increment |
| role_name | varchar(20) | NO   |     | NULL    |                |
| note      | varchar(20) | NO   |     | NULL    |                |
+-----------+-------------+------+-----+---------+----------------+
3 rows in set

mysql> 
  • 初始
mysql> select * from t_role ;
+----+-----------+--------+
| id | role_name | note   |
+----+-----------+--------+
|  1 | admin     | 管理员 |
+----+-----------+--------+
1 row in set

示例

package com.mybatis.study.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;

public class JdbcExample {

    /**
     * 获取数据库连接
     * @return
     */
    private Connection getConnection(){
        Connection connection = null ;
        try {
            /**
             * 异常:class not found 
             * 原因:缺少 jdbc-connection-java.jar 包
             * 解决:eclipse 项目右键,build path --> add External 
             */
            Class.forName("com.mysql.jdbc.Driver");
            String url = "jdbc:mysql://localhost:3306/mybatis?"+
            "zeroDateTimeBehavior=convertToNull&useSSL=false&useUnicode=true&characterEncoding=UTF-8";
            String user = "root" ;
            String pass = "123456" ;
            /**
             * 异常:Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
             * 解决:数据库的连接的URL中添加useSSL=false
             */
            connection = DriverManager.getConnection(url, user, pass);
            /**
             * 异常:java.sql.SQLException: Unknown error 1045
             * 解决:用户名与密码不匹配
             * 验证:使用客户端连接本地数据库,没有记录用户及密码;通过运行(win+r)
             *      mysql -h localhost -u root -p
             *           多次尝试密码后得到正确密码(只有几种可能,逐个尝试)
             */
        } catch (Exception e) {
            Logger.getLogger(JdbcExample.class.getName()).log(Level.SEVERE,null,e);
            return null ;
        }
        return connection ;
    }

    /**
     * 释放资源
     * 注意释放顺序,最后释放连接
     * @param rs
     * @param st
     * @param ct
     */
    private void close(ResultSet rs ,Statement st ,Connection ct){
        try {
            if(null != rs && !rs.isClosed()){
                rs.close();
            }
        } catch (Exception e) {
            Logger.getLogger(JdbcExample.class.getName()).log(Level.SEVERE,null,e);
        }

        try {
            if(null != st && !st.isClosed()){
                st.close();
            }
        } catch (Exception e) {
            Logger.getLogger(JdbcExample.class.getName()).log(Level.SEVERE,null,e);
        }

        try {
            if(null != ct && !ct.isClosed()){
                ct.close();
            }
        } catch (Exception e) {
            Logger.getLogger(JdbcExample.class.getName()).log(Level.SEVERE,null,e);
        }
    }

    /**
     * 数据查询,实体转换
     * @param id
     * @return
     */
    public Role getRole(Long id){
        Connection connection = getConnection();
        PreparedStatement ps = null ;
        ResultSet rs = null ;
        try {
            ps = connection.prepareStatement("select id,role_name,note from t_role where id = ?");
            ps.setLong(1, id);
            rs = ps.executeQuery();
            while(rs.next()){
                Long roleId = rs.getLong("id");
                String roleName = rs.getString("role_name");
                String note = rs.getString("note");
                Role role = new Role();
                role.setId(roleId);
                role.setRoleName(roleName);
                role.setNote(note);
                return role ;
            }
        } catch (Exception e) {
            Logger.getLogger(JdbcExample.class.getName()).log(Level.SEVERE,null,e);
        }finally{
            this.close(rs, ps, connection);
        }

        return null ;
    }

    public static void main(String args[]){
        JdbcExample je = new JdbcExample();
        if(null != je){
            Role role = je.getRole(1L);
            if(null != role)
                System.out.println(role.getId()+":"+role.getRoleName());
        }
    }
}
  • 依赖管理:推荐使用maven
  • 备注信息为调试过程中遇到的异常

数据库连接URL参数说明

  • zeroDateTimeBehavior : 数据类型timestamp当为其赋值0时的处理策略

    • exception:默认值,即抛出SQL state [S1009]. Cannot convert value….的异常;
    • convertToNull:将日期转换成NULL值;
    • round:替换成最近的日期即0001-01-01;
  • 问题延伸:

    • 问题描述:当为timestamp / datetime 赋值 0000-00-00 00:00:00 时,查询时会出现 java.sql.SQLException:Value ‘0000-00-00’ can not be represented as java.sql.Date 异常
    • 解决方案:查询连接添加zeroDateTimeBehavior=round,避免直接抛出异常

参考资料

猜你喜欢

转载自blog.csdn.net/mingyundezuoan/article/details/82319068
今日推荐