jdbc查询

1.引入数据库驱动


    mysql
    mysql-connector-java
    5.1.44

package cn.mln521.jdbc;

import java.sql.*;

public class JdbcTest {
    public static void main(String[] args) {
        Connection connection = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
                //1.注册驱动 tomcat8+ 不需要 会自动注册
                Class.forName("com.mysql.jdbc.Driver");
                //2.通过驱动管理类获取数据库链接
                connection = DriverManager.getConnection("jdbc:mysql:///eesy?characterEncoding=utf-8", "root", "root");
                //3.定义sql  ?表示占位符
                String sql = "select * from user where id = ?";
                //4.获取预处理对象PrepareStatement对象
                ps = connection.prepareStatement(sql);
                //5. 设置参数并执行sql
                ps.setString(1,"41");
                rs = ps.executeQuery();
                //5.处理结果集
                if(rs.next()){
                    System.out.println("姓名:" +rs.getString("username"));
                    System.out.println("生日:" +rs.getString("birthday"));
                }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //释放资源
            if(rs!=null){
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

            if(ps!=null){
                try {
                    ps.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

            if(connection!=null){
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

        }
    }
}

你可能感兴趣的:(mybatis)