java 连接数据库操作

Connection con;
        String driver = "dm.jdbc.driver.DmDriver";
        String url = "jdbc:dm://xxx.xxx.xxx.xxx:5236/xxx?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC";
        String user = "";
        String pwd = "";
  List<Map<String,Object>> resulList=new ArrayList<Map<String, Object>>();此处使用list接收查询数据集合
        try {
            Class.forName(driver);
            con= DriverManager.getConnection(url,user,pwd);
            if(!con.isClosed()){
                Console.log("数据库连接成功!");
                Statement statement=con.createStatement();

                ResultSet rs=statement.executeQuery(sql);
                ResultSetMetaData md=(ResultSetMetaData) rs.getMetaData();

                while (rs.next()){
                    Map<String,Object> rowData=new HashMap<>();
                    for (int i=1;i<=md.getColumnCount();i++){
                        rowData.put(md.getColumnName(i),rs.getObject(i));
                    }
                    resulList.add(rowData);
                }
            }
            return Result.succ(resulList);
        } catch (ClassNotFoundException | SQLException e) {
            return Result.fail("500",e.getMessage());
        }

参考资料:https://docs.oracle.com/javase/7/docs/api/java/sql/ResultSetMetaData.html,https://docs.oracle.com/javase/7/docs/api/java/sql/ResultSet.html

posted @ 2020-12-31 14:54  绯颜旧雨  阅读(166)  评论(0编辑  收藏  举报