jdbc实现对mysql数据库的select

public class JDBCTest4 {
    public static void main(String[] args) {
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        try {
            //1.注册驱动的
            Class.forName("com.mysql.cj.jdbc.Driver");
            //2.获取数据库连接
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/girls?serverTimezone=UTC","root","root");
            //3.获取数据库操作对象
            stmt = conn.createStatement();
            //4.执行sql语句
            String sql = "select * from beauty";
            rs = stmt.executeQuery(sql);
            //5.处理查询结果集
            while (rs.next()){
                String id =rs.getString(1);
                String name =rs.getString(2);
                String sex =rs.getString(3);
                String borndate =rs.getString(4);
                String phone =rs.getString(5);
                String photo =rs.getString(6);
                String boyfriend_id =rs.getString(7);
                System.out.println(id+","+name+","+sex+","+borndate+","+phone+","+photo+","+boyfriend_id);
            }
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if (rs != null){
                    rs.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
            try {
                if (stmt != null){
                    stmt.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
            try {
                if (conn != null){
                    conn.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
经验分享 程序员 微信小程序 职场和发展