哈哈....

	private static SQLStore sqlstore = null;
	private static DBAccess db = null;

	private DBAccess() {
		init();
	}
	//实例化该单例
	public static DBAccess getInstance() {
		if (db == null)
			db = new DBAccess();
		return db;
	}
	//进行初始化,载入sqlstore
	private void init() {
		if (sqlstore == null)
			sqlstore = SQLStore.getInstance();

	}

	//得到一个连接
	public Connection getConnection() {
		DataSource ds = null;
		Connection conn = null;
		try {
			Context ctx = new InitialContext();
			ds = (DataSource) ctx.lookup("java:comp/env/jdbc/oswf");
			conn = ds.getConnection();
		} catch (NamingException ne) {
			ne.printStackTrace();
		} catch (SQLException sqle) {
			sqle.printStackTrace();
		}
		return conn;
	}

	public Vector baseSQLSearch(String sql, Vector params) {
		Connection conn = null;
		ResultSet rs = null;
		Vector<GeneralValueObject> result = new Vector<GeneralValueObject>();

		try {
			conn = getConnection(); //建立连接
			PreparedStatement ps = conn.prepareStatement(sql);
			String strParams = "";
			//将参数传入去
			if (params != null && params.size() > 0) {
				for (int i = 0, s = params.size(); i < s; i++) {
					String param = (String) params.get(i);
					ps.setString(i + 1, param);
					strParams = strParams + "  " + param;
				}
			}

			// 输出sql语句以及参数,用于调试....
			System.out.println("Execute:" + sql);
			System.out.println("Params:" + strParams);
			rs = ps.executeQuery();

			ResultSetMetaData rsmd = ps.getMetaData();
			int columnCount = rsmd.getColumnCount();
			//组装数据
			while (rs.next()) {
				GeneralValueObject gvo = new GeneralValueObject();
				System.out.println("columnCount=" + columnCount);

				if (columnCount > 0)
					for (int i = 1; i <= columnCount; i++) {
						System.out.println(rsmd.getColumnLabel(i));
						System.out.println(rs.getString(i));
						String str = rs.getString(i);
						if (str == null)
							str = "";
						gvo.add(rsmd.getColumnLabel(i).toUpperCase(), str);
					}
				result.add(gvo);
			}

			ps.close();
			rs.close();
		} catch (SQLException sqle) {
			sqle.printStackTrace();
		} finally {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return result;
	}

你可能感兴趣的:(sql,jdbc)