JDBC连接数据库查询

2018-05-31  本文已影响0人  百年叔叔
package com.atguigu.mybatis.test;

import com.atguigu.mybatis.bean.Employee;

import java.sql.*;

/**
 * JDBC连接数据库实例
 *
 * @author 哇哈哈
 */
public class JdbcTest {

    /**
     * 创建一个数据库连接对象
     *
     * @return 返回一个数据库连接对象
     */
    private Connection getConnection() {
        //创建
        Connection connection = null;

        try {
            //数据库的连接信息
            Class.forName("com.mysql.jdbc.Driver");
            String url = "jdbc:mysql://localhost:3306/mybatis";
            String user = "root";
            String password = "root";
            connection = DriverManager.getConnection(url, user, password);

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

        return connection;
    }


    public Employee getEmpById(Long id) {
        Connection connection = getConnection();
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            ps = connection.prepareStatement("select * from tbl_employee where id = ?");
            ps.setLong(1, id);
            rs = ps.executeQuery();
            while (rs.next()) {

                Integer empId = rs.getInt("id");
                String lastName = rs.getString("last_name");
                String email = rs.getString("email");
                String gender = rs.getString("gender");

                Employee emp = new Employee(empId, lastName, email, gender);

                return emp;

            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            this.clone(rs, ps, connection);
        }

        return null;
    }

    /**
     * 关闭连接
     *
     * @param rs
     * @param ps
     * @param connection
     */
    private void clone(ResultSet rs, Statement ps, Connection connection) {
        try {
            if (rs != null && !rs.isClosed()) {
                rs.close();
            }
            if (ps != null && !ps.isClosed()) {
                ps.close();
            }
            if (connection != null && !connection.isClosed()) {
                connection.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        JdbcTest jdbcTest = new JdbcTest();
        Employee empById = jdbcTest.getEmpById(1L);
        System.out.println("Employee=> " + empById);
    }
}

image.png
上一篇下一篇

猜你喜欢

热点阅读