1. 程式人生 > >原生JDBC操作

原生JDBC操作

原生JDBC操作結果集

Class.forName(className);
			Connection con = DriverManager.getConnection(jdbcUrl, username, password);
			PreparedStatement prepareStatement = con.prepareStatement(sql);
			if((sql.contains("select")&&sql.contains("from")) || (sql.contains("SELECT")&&sql.
contains("FROM"))) { ResultSet resultSet = prepareStatement.executeQuery(); ResultSetMetaData metaData = resultSet.getMetaData(); LinkedHashMap<String, Object> map = null; //所有結果集 List<LinkedHashMap<String ,Object>> list=new ArrayList<>(); while
(resultSet.next()) { //把一條記錄放入Map中 map = new LinkedHashMap<String, Object>(); for (int i = 0; i < metaData.getColumnCount(); i++) { String columnLabel = metaData.getColumnLabel(i + 1); Object value =
resultSet.getObject(i + 1); map.put(columnLabel, value); } list.add(map); System.out.println(map); //所有表字段 List<String> titleList=new ArrayList<>(); LinkedHashMap<String,Object> linkedHashMap = list.get(0); Set<String> keySet = linkedHashMap.keySet(); Iterator<String> iterator = keySet.iterator(); while(iterator.hasNext()) { String key = iterator.next(); titleList.add(key); } model.addAttribute("title",titleList); model.addAttribute("list", list); } }else { //增,刪,改操作 boolean flag = prepareStatement.execute(sql); model.addAttribute("flag",flag); }