Get Data from Database without definited Structure

来源:互联网 发布:华为和星环大数据 编辑:程序博客网 时间:2024/05/17 04:32
package tianye.test.rest.controller;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.ResultSetMetaData;import java.sql.SQLException;import java.util.ArrayList;import tianye.test.rest.model.ContactInfoHana;public class DBHana {Connection conn;public DBHana(){try {Class.forName("com.sap.db.jdbc.Driver").newInstance();conn = DriverManager.getConnection("jdbc:sap://localhost:30015/SYSTEM?user=&password=");} catch (Exception ex) {// TODO Auto-generated catch blockSystem.out.println("error");}}public static void main(String args[]){DBHana dbh = new DBHana();try {ArrayList<String[][]> result = dbh.doSelect("select * from contactbook");for(String[][] r:result){for(int i=0;i<r.length;i++){System.out.println(r[i][0] + "," + r[i][1]);}System.out.println("======================");}} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}public ArrayList<String[][]> doSelect(String selectStatement) throws Exception{PreparedStatement ps = conn.prepareStatement(selectStatement.trim());ResultSet rs = ps.executeQuery();ResultSetMetaData rsmd = rs.getMetaData();int colcount = rsmd.getColumnCount();String[] args = new String[colcount];for(int i=0;i<colcount;i++){args[i] = rsmd.getColumnLabel(i+1);}ArrayList<String[][]> returnList = new ArrayList<String[][]>();while(rs.next()){String[][] returnRow = new String[colcount][colcount];for(int i=0;i<args.length;i++){returnRow[i][0] = args[i];returnRow[i][1] = String.valueOf(rs.getObject(args[i]));}returnList.add(returnRow);}return returnList;}// _SELECT_ _FROM_ _WHERE_private int numberOfSubString(String statement, String s){if(statement.contains(s)){int counter = 0;int lastIndex = 0;while(lastIndex != -1){lastIndex = statement.indexOf(s);if (lastIndex != -1)counter ++;}return counter;}elsereturn -1;}}


原创粉丝点击