⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 util.java

📁 derby database source code.good for you.
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
		if (databaseURL.startsWith("jdbc:"))		    util.loadDriverIfKnown(databaseURL);	    if (!databaseURL.startsWith("jdbc:") && jdbcProtocol != null)		databaseURL = jdbcProtocol+databaseURL;	    // Update connInfo for ij system properties and	    // framework network server	    connInfo = updateConnInfo(user, password,connInfo);	    // JDBC driver	    String driver = util.getSystemProperty("driver");	    if (driver == null) {		driver = "org.apache.derby.jdbc.EmbeddedDriver";	    }	    	    loadDriver(driver);		con = DriverManager.getConnection(databaseURL,connInfo);		return con;  	}	    // handle datasource property	    String dsName = util.getSystemProperty("ij.dataSource");	    if (dsName == null)	    	return null;		// Get a new proxied connection through DataSource		Object ds = null; // really javax.sql.DataSource		try {					    Class dc = Class.forName(dsName);		    ds = dc.newInstance();		    		    // set datasource properties		    setupDataSource(ds);	   		    // Java method call "by hand" {  con = ds.getConnection(); }		    // or con = ds.getConnection(user, password)		    				java.lang.reflect.Method m = 				user == null ? dc.getMethod("getConnection", null) :					 dc.getMethod("getConnection", DS_GET_CONN_TYPES);							return (java.sql.Connection) m.invoke(ds,					 user == null ? null : new String[] {user, password});		} catch (InvocationTargetException ite)		{			if (ite.getTargetException() instanceof SQLException)				throw (SQLException) ite.getTargetException();			ite.printStackTrace(System.out);		} catch (Exception e)		{			e.printStackTrace(System.out);		}				return null;   }	public static Properties updateConnInfo(String user, String password, Properties connInfo)	{		String ijGetMessages = util.getSystemProperty("ij.retrieveMessagesFromServerOnGetMessage");		boolean retrieveMessages = false;						// For JCC make sure we set it to retrieve messages		if (isJCCFramework())			retrieveMessages = true;				if (ijGetMessages != null)		{			if (ijGetMessages.equals("false"))				retrieveMessages = false;			else				retrieveMessages = true;					}				if (connInfo == null)			connInfo = new Properties();				if (retrieveMessages == true)		{			connInfo.put("retrieveMessagesFromServerOnGetMessage",						 "true");		}		if (user != null)			connInfo.put("user",user);		if (password != null)			connInfo.put("password", password);				return connInfo;	}	/**		Utility interface that defaults driver and database to null.		@return a connection to the defaultURL if possible; null if not.		@exception SQLException on failure to connect.		@exception ClassNotFoundException on failure to load driver.		@exception InstantiationException on failure to load driver.		@exception IllegalAccessException on failure to load driver.	 */    static public Connection startJBMS() throws SQLException, ClassNotFoundException, InstantiationException, IllegalAccessException {		return startJBMS(null,null);	}		/**	   Utility interface that defaults connInfo to null	   <p>		@param defaultDriver the driver to use if no property value found		@param defaultURL the database URL to use if no property value found		@return a connection to the defaultURL if possible; null if not.		@exception SQLException on failure to connect.		@exception ClassNotFoundException on failure to load driver.		@exception InstantiationException on failure to load driver.		@exception IllegalAccessException on failure to load driver.	 */    static public Connection startJBMS(String defaultDriver, String defaultURL) 			throws SQLException, ClassNotFoundException, InstantiationException,				   IllegalAccessException {		return startJBMS(defaultDriver,defaultURL,null);			}	//-----------------------------------------------------------------	// Methods for displaying and checking results	// See org.apache.derby.tools.JDBCDisplayUtil for more general displays.	/**		Display a vector of strings to the out stream.	 */	public static void DisplayVector(LocalizedOutput out, Vector v) {		int l = v.size();		for (int i=0;i<l;i++)			out.println(v.elementAt(i));	}	/**		Display a vector of statements to the out stream.	public static void DisplayVector(AppStreamWriter out, Vector v, Connection conn) throws SQLException {		int l = v.size();AppUI.out.println("SIZE="+l);		for (int i=0;i<l;i++) {			Object o = v.elementAt(i);			if (o instanceof Integer) { // update count				JDBCDisplayUtil.DisplayUpdateCount(out,((Integer)o).intValue());			} else { // o instanceof ResultSet			    JDBCDisplayUtil.DisplayResults(out,(ResultSet)o,conn);				((ResultSet)o).close(); // release the result set			}		}	}	 */	/**		Display a statement that takes parameters by		stuffing it with rows from the result set and		displaying each result each time through.		Deal with autocommit behavior along the way.		@exception SQLException thrown on db error		@exception ijException thrown on ij error	 */	public static void DisplayMulti(LocalizedOutput out, PreparedStatement ps,		ResultSet rs, Connection conn) throws SQLException, ijException {		boolean autoCommited = false; // mark if autocommit in place		boolean exec = false; // mark the first time through		boolean anotherUsingRow = false;	// remember if there's another row 											// from using.		ResultSetMetaData rsmd = rs.getMetaData();		int numCols = rsmd.getColumnCount();		/* NOTE: We need to close the USING RS first		 * so that RunTimeStatistic gets info from		 * the user query.		 */		anotherUsingRow = rs.next();		while (! autoCommited && anotherUsingRow) {			// note the first time through			if (!exec) {				exec = true;				// send a warning if additional results may be lost				if (conn.getAutoCommit()) {					out.println(LocalizedResource.getMessage("IJ_IjWarniAutocMayCloseUsingResulSet"));					autoCommited = true;				}			}			// We need to make sure we pass along the scale, because			// setObject assumes a scale of zero (beetle 4365)			for (int c=1; c<=numCols; c++) {				int sqlType = rsmd.getColumnType(c);								if (sqlType == Types.DECIMAL)				{					if (util.HAVE_BIG_DECIMAL)					{						ps.setObject(c,rs.getObject(c),								 sqlType,								 rsmd.getScale(c));												}					else					{						// In J2ME there is no object that represents						// a DECIMAL value. By default use String to						// pass values around, but for integral types						// first convert to a integral type from the DECIMAL						// because strings like 3.4 are not convertible to						// an integral type.						switch (ps.getMetaData().getColumnType(c))						{						case Types.BIGINT:							ps.setLong(c, rs.getLong(c));						    break;						case Types.INTEGER:						case Types.SMALLINT:						case Types.TINYINT:							ps.setInt(c, rs.getInt(c));							break;						default:							ps.setString(c,rs.getString(c));						    break;						}													}									}				else				{					ps.setObject(c,rs.getObject(c),							 sqlType);									}											}			// Advance in the USING RS			anotherUsingRow = rs.next();			// Close the USING RS when exhausted and appropriate			// NOTE: Close before the user query			if (! anotherUsingRow || conn.getAutoCommit()) //if no more rows or if auto commit is on, close the resultset			{				rs.close();			}			/*				4. execute the statement against those parameters			 */			ps.execute();			JDBCDisplayUtil.DisplayResults(out,ps,conn);			/*				5. clear the parameters			 */			ps.clearParameters();		}		if (!exec) {			rs.close(); //this means, using clause didn't qualify any rows. Just close the resultset associated with using clause			throw ijException.noUsingResults();		}		// REMIND: any way to look for more rsUsing rows if autoCommit?		// perhaps just document the behavior... 	}	static final String getSystemProperty(String propertyName) {		try		{			if (propertyName.startsWith("ij.") || propertyName.startsWith("derby."))			{				util u = new util();				u.key = propertyName;				return (String) java.security.AccessController.doPrivileged(u);			}			else			{				return System.getProperty(propertyName);			}		} catch (SecurityException se) {			return null;		}	}	private String key;	public final Object run() {		return System.getProperty(key);	}	/** 	 * Read a set of properties from the received input stream, strip	 * off any excess white space that exists in those property values,	 * and then add those newly-read properties to the received	 * Properties object; not explicitly removing the whitespace here can	 * lead to problems.	 *	 * This method exists because of the manner in which the jvm reads	 * properties from file--extra spaces are ignored after a _key_, but	 * if they exist at the _end_ of a property decl line (i.e. as part	 * of a _value_), they are preserved, as outlined in the Java API:	 *	 * "Any whitespace after the key is skipped; if the first non-	 * whitespace character after the key is = or :, then it is ignored 	 * and any whitespace characters after it are also skipped. All	 * remaining characters on the line become part of the associated	 * element string."	 *	 * @param iStr An input stream from which the new properties are to be	 *  loaded (should already be initialized).	 * @param prop A set of properties to which the properties from	 *  iStr will be added (should already be initialized).	 * @return A final properties set consisting of 'prop' plus all	 * properties loaded from 'iStr' (with the extra whitespace (if any)	 *  removed from all values), will be returned via the parameter.	 *		Copied here to avoid dependency on an engine class.	 **/	private static void loadWithTrimmedValues(InputStream iStr,		Properties prop) throws IOException {		// load the properties from the received input stream.		Properties p = new Properties();		p.load(iStr);		// Now, trim off any excess whitespace, if any, and then		// add the properties from file to the received Properties		// set.		for (java.util.Enumeration propKeys = p.propertyNames();		  propKeys.hasMoreElements();) {		// get the value, trim off the whitespace, then store it		// in the received properties object.			String tmpKey = (String)propKeys.nextElement();			String tmpValue = p.getProperty(tmpKey);			tmpValue = tmpValue.trim();			prop.put(tmpKey, tmpValue);		}		return;	}	private static final String[][] protocolDrivers =		{		  { "jdbc:derby:net:",			"com.ibm.db2.jcc.DB2Driver"},		  { "jdbc:derby://",            "org.apache.derby.jdbc.ClientDriver"},		  { "jdbc:derby:",				"org.apache.derby.jdbc.EmbeddedDriver" },		};	/**		Find the appropriate driver and load it, given a JDBC URL.		No action if no driver known for a given URL.		@param jdbcProtocol the protocol to try.		@exception ClassNotFoundException if unable to			locate class for driver.		@exception InstantiationException if unable to			create an instance.		@exception IllegalAccessException if driver class constructor not visible.	 */	public static void loadDriverIfKnown(String jdbcProtocol) throws ClassNotFoundException, InstantiationException, IllegalAccessException {		for (int i=0; i < protocolDrivers.length; i++) {			if (jdbcProtocol.startsWith(protocolDrivers[i][0])) {				loadDriver(protocolDrivers[i][1]);				break; // only want the first one			}		}	}	/**		Load a driver given a class name.		@exception ClassNotFoundException if unable to			locate class for driver.		@exception InstantiationException if unable to			create an instance.		@exception IllegalAccessException if driver class constructor not visible.	 */	public static void loadDriver(String driverClass) throws ClassNotFoundException, InstantiationException, IllegalAccessException {        Class.forName(driverClass).newInstance();	}	/**	 * Used to determine if this is a JCC testing framework 	 * So that retrieveMessages can be sent.  The plan is to have  	 * ij will retrieve messages by default and not look at the testing 	 * frameworks. So, ulitmately  this function will look at the driver	 * rather than the framework.	 * 	 * @return true if the framework contains Net or JCC.	 */	private static boolean isJCCFramework()	{		String framework = util.getSystemProperty("framework");		return ((framework != null)  &&			((framework.toUpperCase(Locale.ENGLISH).equals("DERBYNET")) ||			 (framework.toUpperCase(Locale.ENGLISH).indexOf("JCC") != -1)));	}	}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -