原生查询数据库流程

在java基础学习中,其中就有连接数据库并查询数据,这其中没有用到任何框架,全部都是原生java代码。步骤如下:

1、导入jar包

在idea中,打开项目结构视图,导入需要依赖的jar包:

2、加载数据库驱动类,并获取连接

编写一个工具类,用于加载数据库驱动类,并用驱动管理器来创建连接对象

public class ConnUtils {
    
    //数据库驱动的完整类名
    private static String driver = "com.mysql.jdbc.Driver";
    //连接数据库的url
    private static String url = "jdbc:mysql://localhost:3306/mydb?useUnicode=true&characterEncoding=utf-8";
    //连接数据库的用户名
    private static String user = "root";
    //连接数据库的密码
    private static String password = "root";
    
    //在静态代码块中进行驱动注册(也就是类加载)
    static {
        try {
            Class.forName(driver);
        }catch(Exception e) {
            throw new RuntimeException(e);
        }
    }
    
    /**
     * 获取数据库连接的静态方法
     * @return
     */
    public static Connection getConnection() {
        //通过驱动管理器来创建连接对象
        try {
            return DriverManager.getConnection(url, user, password);
        }catch(Exception e) {
            throw new RuntimeException(e);
        }
    }
}

3、查询数据库并返回结果

编写数据访问类:

public class UserDao{
    /**
     * 查询所有,无条件
     * @return
     */
    public List<Users> getUsers(){
        //1、定义操作数据库的sql语句
        String sql = "select * from user_info";
        List<Users> users = new ArrayList<>();
        try(
            //2、获取连接
            Connection connection = ConnUtils.getConnection();
            //3、使用PreparedStatement对象预编译sql语句
            PreparedStatement ps = connection.prepareStatement(sql);
            //4、定义结果集,封装查询的数据
            ResultSet rs = ps.executeQuery()
                ) {
            //5、遍历结果集,将结果集中的数据封装到实体中
            while (rs.next()){
                Users user = new Users();
                //可以通过索引获取,从1开始
//                user.setUid(rs.getInt(1));
//                user.setUserName(rs.getString(2));
//                user.setAge(rs.getInt(3));
                //也可以通过数据库中的字段名获取,这样做更精确
                user.setUid(rs.getInt("u_id"));
                user.setUserName(rs.getString("u_name"));
                //将实体添加到集合中
                users.add(user);
            }
            //6、返回集合
            return users;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
    
    /**
     * 根据id查询出一条数据
     * @param id
     * @return
     */
    public Users getUserById(int id){
        //1、定义访问数据库的sql语句
        String sql = "select * from user_info where u_id = ?";
        try(
            //2、获取连接
            Connection conn = ConnUtils.getConnection();
            //3、使用PreparedStatement对象预编译sql语句
            PreparedStatement ps = conn.prepareStatement(sql)) {
            //参数替换,填充数据,替换sql语句中的 ? 号,索引从1开始
            ps.setInt(1, id);
            //4、定义结果集
            try(ResultSet rs = ps.executeQuery()){
                //封装查询的数据
                Users user = new Users();
                if (rs.next()){
                    user.setUid(rs.getInt("u_id"));
                    user.setUserName(rs.getString("u_name"));
                }
                return user;
            }catch(SQLException e){
                throw e;
            }
        }catch(Exception e){
            throw  new RuntimeException(e);
        }
    }
    
    /**
     * 添加一条数据
     * @param user
     * @return 返回受影响的行数
     */
    public int addUser(Users user){
        //定义访问数据库的sql语句
        String sql = "insert into user_info values (?,?)";
        try(Connection connection = ConnUtils.getConnection();
        PreparedStatement ps = connection.prepareStatement(sql)) {
            ps.setInt(1, user.getUid());
            ps.setString(2, user.getUserName());
            return ps.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
}

4、关闭连接

在jdk7中,新增了自动关闭资源的try语句,语法是在try后面加一个圆括号,里面可以定义一个或多个资源,此处的资源都是哪些必须在程序结束时关闭的资源(如这里的数据库连接),try语句会在该语句结束时自动关闭这些资源,具体语法可以查看上面的代码。

 

原文地址:https://www.cnblogs.com/zhangcaihua/p/13141356.html