JDBC查询 方式 java, sql, select,数据库

JDBC查询 方式 java, sql, select,数据库,第1张

JDBC查询 方式 java, sql, select,数据库 数据库 1.代码优化 1.查询一个(不通用
public static void queryOne(String sql) throws Exception {

    Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/bailiban", "root", "123456");
    Statement stat = conn.createStatement();
    ResultSet query = stat.executeQuery(sql);
    if (query.next()){
        String id = query.getString("id");
        String name = query.getString("name");
        String sex = query.getString("sex");
        String age = query.getString("age");
        System.out.println(id+"--"+name+"--"+sex+"--"+age);
    }
    System.out.println(query.next());
    stat.close();
    conn.close();
}
2.查询多个(不通用)
public static void queryMore(String sql) throws Exception {

    Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/bailiban", "root", "123456");
    Statement stat = conn.createStatement();
    ResultSet query = stat.executeQuery(sql);
    while (query.next()){
        String id = query.getString("id");
        String name = query.getString("name");
        String sex = query.getString("sex");
        String age = query.getString("age");
        System.out.println(id+"--"+name+"--"+sex+"--"+age);
    }
    System.out.println(query.next());
    stat.close();
    conn.close();
}
3.通用的代码
public static void queryMorePlus(String sql) throws Exception {

    
    Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/bailiban", "root", "123456");

    
    Statement stat = conn.createStatement();

    
    ResultSet rs = stat.executeQuery(sql);

    
    ResultSetmetaData md = rs.getmetaData();

    
    int count = md.getColumnCount();

    
    while (rs.next()){
        for (int i = 1; i <= count; i++) {
            Object object = rs.getObject(i);
            System.out.print(object);
        }
        System.out.println();
    }

    
    stat.close();
    conn.close();
}

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

原文地址: http://outofmemory.cn/zaji/5581820.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-14
下一篇 2022-12-15

发表评论

登录后才能评论

评论列表(0条)

保存