package com.offcn.TestUnti;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class MySqlUtil {
	//查询表名tableName的条件是condition的结果集
	public ResultSet selectFromDB(String tableName, String condition) throws Exception {
		Connection conn = null;
		String sql;
		ResultSet rs = null;
		String url = ReadProperties.GetPropertyByKey("sqlurl");

		Class.forName("com.mysql.jdbc.Driver");
		conn = DriverManager.getConnection(url);
		Statement stmt = conn.createStatement();
		sql = "select * from " + tableName + " where " + condition;
//			 System.out.println("select_sql="+sql);
		rs = stmt.executeQuery(sql);
		return rs;

	}
	
	//将JDBC ResultSet结果集转成List
	public static List<Map<String, Object>>  ResultSetToList(ResultSet rs) throws Exception {
		List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
		ResultSetMetaData md = rs.getMetaData(); //获得结果集结构信息,元数据
		int columnCount = md.getColumnCount();   //获得列数 
		while (rs.next()) {
			Map<String,Object> rowData = new HashMap<String,Object>();
			for (int i = 1; i <= columnCount; i++) {
				rowData.put(md.getColumnName(i), rs.getObject(i));
			}
			list.add(rowData);
 
		}
		return list;

	}
}
