List of usage examples for java.sql Statement getResultSet
ResultSet getResultSet() throws SQLException;
ResultSet
object. From source file:com.alibaba.cobar.manager.test.ConnectionTest.java
/** * @param args// w ww.ja va 2 s . c o m */ public static void main(String[] args) { try { BasicDataSource ds = new BasicDataSource(); ds.setUsername("test"); ds.setPassword(""); ds.setUrl("jdbc:mysql://10.20.153.178:9066/"); ds.setDriverClassName("com.mysql.jdbc.Driver"); ds.setMaxActive(-1); ds.setMinIdle(0); ds.setTimeBetweenEvictionRunsMillis(600000); ds.setNumTestsPerEvictionRun(Integer.MAX_VALUE); ds.setMinEvictableIdleTimeMillis(GenericObjectPool.DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS); Connection conn = ds.getConnection(); Statement stm = conn.createStatement(); stm.execute("show @@version"); ResultSet rst = stm.getResultSet(); rst.next(); String version = rst.getString("VERSION"); System.out.println(version); } catch (Exception exception) { System.out.println("10.20.153.178:9066 " + exception.getMessage() + exception); } }
From source file:Main.java
public static void main(String args[]) throws Exception { Connection conn = null;//w w w.j a va 2 s. c om Statement s = null; Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); conn = DriverManager.getConnection("jdbc:odbc:Driver={SQL Server};" + "Server=.\\SQLEXPRESS;" + "Trusted_Connection=yes;" + "Database=myDb"); s = conn.createStatement(); s.executeQuery("SELECT * FROM dbo.SalesSummary WHERE 0 = 1"); ResultSet rs = s.getResultSet(); ResultSetMetaData rsmd = rs.getMetaData(); for (int i = 1; i <= rsmd.getColumnCount(); i++) { System.out.println(String.format("-- Column %d --", i)); System.out.println(String.format("Column name: %s", rsmd.getColumnName(i))); System.out.println(String.format("Database-specific type name: %s", rsmd.getColumnTypeName(i))); System.out.println(String.format("Column size (DisplaySize): %d", rsmd.getColumnDisplaySize(i))); System.out.println(String.format("java.sql.Type of column: %d", rsmd.getColumnType(i))); System.out.println(); } s.close(); conn.close(); }
From source file:ExecuteSQL.java
public static void main(String[] args) { Connection conn = null; // Our JDBC connection to the database server try {// ww w .jav a 2s .c om String driver = null, url = null, user = "", password = ""; // Parse all the command-line arguments for (int n = 0; n < args.length; n++) { if (args[n].equals("-d")) driver = args[++n]; else if (args[n].equals("-u")) user = args[++n]; else if (args[n].equals("-p")) password = args[++n]; else if (url == null) url = args[n]; else throw new IllegalArgumentException("Unknown argument."); } // The only required argument is the database URL. if (url == null) throw new IllegalArgumentException("No database specified"); // If the user specified the classname for the DB driver, load // that class dynamically. This gives the driver the opportunity // to register itself with the DriverManager. if (driver != null) Class.forName(driver); // Now open a connection the specified database, using the // user-specified username and password, if any. The driver // manager will try all of the DB drivers it knows about to try to // parse the URL and connect to the DB server. conn = DriverManager.getConnection(url, user, password); // Now create the statement object we'll use to talk to the DB Statement s = conn.createStatement(); // Get a stream to read from the console BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); // Loop forever, reading the user's queries and executing them while (true) { System.out.print("sql> "); // prompt the user System.out.flush(); // make the prompt appear now. String sql = in.readLine(); // get a line of input from user // Quit when the user types "quit". if ((sql == null) || sql.equals("quit")) break; // Ignore blank lines if (sql.length() == 0) continue; // Now, execute the user's line of SQL and display results. try { // We don't know if this is a query or some kind of // update, so we use execute() instead of executeQuery() // or executeUpdate() If the return value is true, it was // a query, else an update. boolean status = s.execute(sql); // Some complex SQL queries can return more than one set // of results, so loop until there are no more results do { if (status) { // it was a query and returns a ResultSet ResultSet rs = s.getResultSet(); // Get results printResultsTable(rs, System.out); // Display them } else { // If the SQL command that was executed was some // kind of update rather than a query, then it // doesn't return a ResultSet. Instead, we just // print the number of rows that were affected. int numUpdates = s.getUpdateCount(); System.out.println("Ok. " + numUpdates + " rows affected."); } // Now go see if there are even more results, and // continue the results display loop if there are. status = s.getMoreResults(); } while (status || s.getUpdateCount() != -1); } // If a SQLException is thrown, display an error message. // Note that SQLExceptions can have a general message and a // DB-specific message returned by getSQLState() catch (SQLException e) { System.err.println("SQLException: " + e.getMessage() + ":" + e.getSQLState()); } // Each time through this loop, check to see if there were any // warnings. Note that there can be a whole chain of warnings. finally { // print out any warnings that occurred SQLWarning w; for (w = conn.getWarnings(); w != null; w = w.getNextWarning()) System.err.println("WARNING: " + w.getMessage() + ":" + w.getSQLState()); } } } // Handle exceptions that occur during argument parsing, database // connection setup, etc. For SQLExceptions, print the details. catch (Exception e) { System.err.println(e); if (e instanceof SQLException) System.err.println("SQL State: " + ((SQLException) e).getSQLState()); System.err.println( "Usage: java ExecuteSQL [-d <driver>] " + "[-u <user>] [-p <password>] <database URL>"); } // Be sure to always close the database connection when we exit, // whether we exit because the user types 'quit' or because of an // exception thrown while setting things up. Closing this connection // also implicitly closes any open statements and result sets // associated with it. finally { try { conn.close(); } catch (Exception e) { } } }
From source file:ExecuteMethod.java
public static void processExecute(Statement stmt, boolean executeResult) throws SQLException { if (!executeResult) { int updateCount = stmt.getUpdateCount(); System.out.println(updateCount + " row was " + "inserted into Employee table."); } else {//ww w. j av a2 s . c o m ResultSet rs = stmt.getResultSet(); while (rs.next()) { System.out.println(rs.getInt("SSN") + rs.getString("Name") + rs.getDouble("Salary") + rs.getDate("Hiredate") + rs.getInt("Loc_id")); } } }
From source file:org.apache.stratos.status.monitor.internal.core.MySQLConnector.java
/** * Gets the list of all the service state details. * * @return the list of the service state details. * @throws Exception, if the retrieval of the service state details failed. */// w w w. j a v a2s . c om public static List<ServiceStateDetailInfoBean> getAllServiceStateDetail() throws Exception { List<ServiceStateDetailInfoBean> stateDetailList = new ArrayList<ServiceStateDetailInfoBean>(); ResultSet rs; Statement stmtCon = conn.createStatement(); String sql = StatusMonitorConstants.GET_ALL_STATE_DETAIL_SQL; stmtCon.executeQuery(sql); rs = stmtCon.getResultSet(); String service; String serviceStateDetail; Timestamp stateLoggedTime; Timestamp detailLoggedTime; ServiceStateDetailInfoBean serviceStateDetailInfoBean; try { while (rs.next()) { serviceStateDetailInfoBean = new ServiceStateDetailInfoBean(); service = rs.getString(StatusMonitorConstants.SERVICE_WSL_NAME); stateLoggedTime = rs.getTimestamp(StatusMonitorConstants.SERVICE_STATE_WSL_TIMESTAMP); detailLoggedTime = rs.getTimestamp(StatusMonitorConstants.SERVICE_STATE_DETAIL_WSL_TIMESTAMP); serviceStateDetail = rs.getString(StatusMonitorConstants.SERVICE_STATE_DETAIL); serviceStateDetailInfoBean.setService(service); serviceStateDetailInfoBean.setStateLoggedTime(stateLoggedTime.getTime()); serviceStateDetailInfoBean.setServiceStateDetail(serviceStateDetail); serviceStateDetailInfoBean.setDetailLoggedTime(detailLoggedTime.getTime()); stateDetailList.add(serviceStateDetailInfoBean); } } catch (SQLException e) { String msg = "Getting the serviceID failed"; log.error(msg, e); throw new SQLException(msg, e); } finally { rs.close(); stmtCon.close(); } return stateDetailList; }
From source file:org.apache.falcon.regression.core.util.HiveUtil.java
/** * Run a sql using given connection.//from w w w.ja v a 2 s . com * @param connection The connection to be used for running sql * @param sql the sql to be run * @throws SQLException * @return output of the query as a List of strings */ public static List<String> runSql(Connection connection, String sql) throws SQLException { Statement stmt = null; try { stmt = connection.createStatement(); LOGGER.info("Executing: " + sql); stmt.execute(sql); final ResultSet resultSet = stmt.getResultSet(); if (resultSet != null) { final List<String> output = fetchRows(resultSet); LOGGER.info("Results are:\n" + StringUtils.join(output, "\n")); return output; } LOGGER.info("Query executed."); } finally { if (stmt != null) { stmt.close(); } } return new ArrayList<>(); }
From source file:org.apache.stratos.status.monitor.core.jdbc.MySQLConnectionInitializer.java
/** * Gets state name with the given state id * * @return state name/*w w w.j av a 2s. c o m*/ * {Up & Running, Broken, Down, Fixed. } * @throws java.sql.SQLException, if the retrieval of the list of states failed. */ private static List<String> getStateNameList() throws SQLException { List<String> stateList = new ArrayList<String>(); ResultSet rs; Statement stmtCon = conn.createStatement(); String sql = StatusMonitorConstants.GET_STATE_NAME_SQL; stmtCon.executeQuery(sql); rs = stmtCon.getResultSet(); String stateName; try { while (rs.next()) { stateName = rs.getString(StatusMonitorConstants.NAME); stateList.add(stateName); } } catch (SQLException e) { String msg = "Getting the serviceID failed"; log.error(msg, e); throw new SQLException(msg, e); } finally { rs.close(); stmtCon.close(); } return stateList; }
From source file:org.apache.stratos.status.monitor.core.jdbc.MySQLConnectionInitializer.java
/** * Gets the list of available services/*from w w w . jav a2s . c o m*/ * * @return List of services * @throws SQLException, if getting the service name failed. */ private static List<String> getServiceNamesList() throws SQLException { List<String> serviceList = new ArrayList<String>(); ResultSet rs; Statement stmtCon = conn.createStatement(); String sql = StatusMonitorConstants.GET_SERVICE_NAME_SQL; stmtCon.executeQuery(sql); rs = stmtCon.getResultSet(); String serviceName; try { while (rs.next()) { serviceName = rs.getString(StatusMonitorConstants.NAME); serviceList.add(serviceName); } } catch (SQLException e) { String msg = "Getting the service name list failed"; log.error(msg, e); throw new SQLException(msg, e); } finally { rs.close(); stmtCon.close(); } return serviceList; }
From source file:org.apache.stratos.status.monitor.internal.core.MySQLConnector.java
/** * Gets the service state ID from the service ID * * @param serviceID: int//from w w w. jav a 2 s.com * @return service state ID * @throws java.sql.SQLException, if the retrieval of the service state failed. */ public static ServiceStateInfoBean getServiceState(int serviceID) throws SQLException { ResultSet rs; Statement stmtCon = conn.createStatement(); String sql = StatusMonitorConstants.GET_SERVICE_STATE_SQL + serviceID + StatusMonitorConstants.ORDER_BY_TIMESTAMP_SQL; stmtCon.executeQuery(sql); rs = stmtCon.getResultSet(); int stateID; Timestamp date; ServiceStateInfoBean serviceStateInfoBean = new ServiceStateInfoBean(); try { while (rs.next()) { stateID = rs.getInt(StatusMonitorConstants.STATE_ID); date = rs.getTimestamp(StatusMonitorConstants.TIMESTAMP); serviceStateInfoBean.setDate(date.getTime()); serviceStateInfoBean.setService(serviceList.get(serviceID - 1)); serviceStateInfoBean.setServiceID(serviceID); serviceStateInfoBean.setServiceState(statusList.get(stateID - 1)); } } catch (SQLException e) { String msg = "Getting the service state failed"; log.error(msg, e); throw new SQLException(msg, e); } finally { rs.close(); stmtCon.close(); } return serviceStateInfoBean; }
From source file:net.xy.jcms.controller.configurations.parser.TranslationDBConnector.java
/** * loads/parses an single translation rule * /*from w ww. j av a2s . co m*/ * @param dac * @param connection * @param parentLoader * @return * @throws SQLException * @throws ClassNotFoundException */ private static TranslationRule[] loadTranslations(final IDataAccessContext dac, final Connection connection, final ClassLoader loader) throws SQLException, ClassNotFoundException { final Statement query = connection.createStatement(); if (!query.execute("SELECT * FROM Translations WHERE Enabled = true;")) { throw new IllegalArgumentException("Retrieving translations from DB returned no results."); } final ResultSet result = query.getResultSet(); final List<TranslationRule> cases = new LinkedList<TranslationRule>(); while (result.next()) { cases.add(loadRule(dac, result, connection, loader)); } return cases.toArray(new TranslationRule[cases.size()]); }