jdbc实现对mysql数据库的select

jdbc实现对mysql数据库的select,第1张

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();
            }
        }
    }
}

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/739214.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-04-28
下一篇2022-04-28

发表评论

登录后才能评论

评论列表(0条)

    保存