zoukankan      html  css  js  c++  java
  • jdbc不写bean类还能返回查询的结果

    ResultSetMetaData metaData = rs.getMetaData();

    jdbc中有一步是返回结果集,在结果集中有个getMetaData()的方法就可以得到数据库中的所有值,例如字段名、行数、列数等等可以用debug看看

    以下是jdbc的增删改   和   查的封装类,不用写bean类就可直接使用

    package com.hp.factory;

    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.ResultSetMetaData;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    public class AllFactory {
        final static String url = "jdbc:mysql://localhost:3306/project01?unicode=true&characterEncoding=UTF-8";
        final static String user = "root";
        final static String password = "root";
        final static String driver = "com.mysql.jdbc.Driver";
        public static Connection getConn()throws Exception {
            Class.forName(driver);
            return DriverManager.getConnection(url, user, password);
        }
        public static List<Map<String, Object>> executeQuery(String sql)throws Exception {
            List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
            Connection conn = getConn();
            PreparedStatement ps = conn.prepareStatement(sql);
            ResultSet rs = ps.executeQuery();
            while (rs.next()) {
                ResultSetMetaData metaData = rs.getMetaData();
                Map<String, Object> map = new HashMap<String, Object>();
                for(int i=1;i<=metaData.getColumnCount();i++) {
                    map.put(metaData.getColumnLabel(i), rs.getObject(i));
                }
                list.add(map);
            }
            rs.close();
            ps.close();
            conn.close();
            return list;
        }
        public static int excuteUpdate(String sql) throws Exception {
            Connection conn = getConn();
            PreparedStatement ps = conn.prepareStatement(sql);
            int i = ps.executeUpdate();
            ps.close();
            conn.close();
            return i;
        }

    }

  • 相关阅读:
    【回顾整理】HTML+CSS个的两个实战项目
    【转】tkinter实现的文本编辑器
    迟到的tkinter---学校选课刷屏器
    调用有道翻译API
    【leetCode】3Sum Closest
    【LeedCode】3Sum
    【LeedCode】String to integer(atoi)
    【LeetCode】Reverse digits of an integer
    前端工程师必备PS技能
    【LeetCode】Add Two Numbers
  • 原文地址:https://www.cnblogs.com/lihui123/p/13842863.html
Copyright © 2011-2022 走看看