private void initFromDatabase() throws SQLException, BlockStoreException { Statement s = conn.get().createStatement(); ResultSet rs; rs = s.executeQuery("SELECT value FROM settings WHERE name = '" + CHAIN_HEAD_SETTING + "'"); if (!rs.next()) { throw new BlockStoreException("corrupt Postgres block store - no chain head pointer"); } Sha256Hash hash = new Sha256Hash(rs.getBytes(1)); rs.close(); this.chainHeadBlock = get(hash); this.chainHeadHash = hash; if (this.chainHeadBlock == null) { throw new BlockStoreException("corrupt Postgres block store - head block not found"); } rs = s.executeQuery( "SELECT value FROM settings WHERE name = '" + VERIFIED_CHAIN_HEAD_SETTING + "'"); if (!rs.next()) { throw new BlockStoreException( "corrupt Postgres block store - no verified chain head pointer"); } hash = new Sha256Hash(rs.getBytes(1)); rs.close(); s.close(); this.verifiedChainHeadBlock = get(hash); this.verifiedChainHeadHash = hash; if (this.verifiedChainHeadBlock == null) { throw new BlockStoreException("corrupt Postgres block store - verified head block not found"); } }
static void attributeMean() { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); con = DriverManager.getConnection("jdbc:odbc:jbdb", "system", "tiger"); Statement meanQuery = con.createStatement(); ResultSet mean = meanQuery.executeQuery("select AVG(sal) from employ where sal IS NOT NULL"); if (mean.next()) { fill = con.createStatement(); fill.executeUpdate("UPDATE employ set sal = COALESCE(sal," + mean.getInt(1) + ")"); } /*fill = con.createStatement(); fill.executeUpdate("UPDATE employ set sal = COALESCE(sal,AVG(sal))");*/ st = con.createStatement(); rs = st.executeQuery("select * from employ"); System.out.println("Sno\tName\tSalary\tGPF\tGrade"); while (rs.next()) { System.out.println( ">>" + rs.getString(1) + "\t" + rs.getString(2) + "\t" + rs.getString(3) + "\t" + rs.getString(4) + "\t" + rs.getString(5)); } } catch (Exception e) { System.out.println("Error: " + e); } }
/** * Test importing an unsupported field e.g. datetime, the program should continue and assign null * value to the field. * * @throws Exception */ @Test public void testImportUnsupportedField() throws Exception { ConnectionProperties p = getConnectionProperties(); Connection cn = DatabaseConnection.getConnection(p); try { List<Field> verifiedFields = new Vector<Field>(); String[] fields = "ListingId, Title".split(","); String tableName = "Listings"; DatabaseConnection.verifyTable(p, tableName, fields, verifiedFields); Collection<JsonNode> importNodes = new LinkedList<JsonNode>(); JsonNodeFactory f = JsonNodeFactory.instance; int listingId = 1559350; ObjectNode n; n = new ObjectNode(f); n.put("ListingId", listingId); importNodes.add(n); JsonArrayImporter importer = new JsonArrayImporter(p); importer.doImport(tableName, verifiedFields, importNodes); Statement st = cn.createStatement(); ResultSet rs = st.executeQuery("SELECT ListingId, Title FROM Listings"); assertTrue("Expected result set to contain a record", rs.next()); assertEquals(listingId, rs.getInt("ListingId")); assertEquals(null, rs.getString("Title")); } finally { cn.close(); } }
static void probableValue() { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); con = DriverManager.getConnection("jdbc:odbc:jbdb", "system", "tiger"); Statement freqQuery = con.createStatement(); ResultSet freq = freqQuery.executeQuery( "select sal,count(*) as total from employ group by sal order by total desc"); if (freq.next()) { fill = con.createStatement(); fill.executeUpdate("UPDATE employ set sal = COALESCE(sal," + freq.getInt(1) + ")"); } st = con.createStatement(); rs = st.executeQuery("select * from employ"); System.out.println(">>Sno\tName\tSalary\tGPF\tGrade"); while (rs.next()) { System.out.println( ">>" + rs.getString(1) + "\t" + rs.getString(2) + "\t" + rs.getString(3) + "\t" + rs.getString(4) + "\t" + rs.getString(5)); } } catch (Exception e) { System.out.println("Error: " + e); } }
/** * Remove a student from a particular course. Also Deletes all the quiz vizualisation files in the * student's directory which relates to the course. Caution: vizualisation file will be deleted * eventhough it also relates to another course if the student is also registered to that course. * (FIX ME!) Throws InvalidDBRequestException if the student is not registered in the course, * error occured during deletion, or other exception occured. * * @param username student's user name * @param courseID course id (course number + instructor name) * @throws InvalidDBRequestException */ public void deleteStudent(String username, String courseID) throws InvalidDBRequestException { try { Class.forName(GaigsServer.DBDRIVER); db = DriverManager.getConnection(GaigsServer.DBURL, GaigsServer.DBLOGIN, GaigsServer.DBPASSWD); Statement stmt = db.createStatement(); ResultSet rs; int count = 0; // check if student registered to the course rs = stmt.executeQuery( "select * from courseRoster where course_id = '" + courseID + "' and user_login = '******'"); if (!rs.next()) throw new InvalidDBRequestException("Student is not registered to the course"); // remove student from the course count = stmt.executeUpdate( "delete from courseRoster where course_id = '" + courseID + "' and user_login = '******'"); if (count != 1) throw new InvalidDBRequestException("Error occured during deletion!"); // delete the quiz visualization files rs = stmt.executeQuery( "select distinct unique_id, s.test_name from scores s, courseTest t " + "where s.test_name = t.test_name " + "and course_id = '" + courseID + "' " + "and user_login = '******'"); while (rs.next()) { deleteVisualization(rs.getString(1), username, rs.getString(2)); count = stmt.executeUpdate("delete from scores where unique_id = " + rs.getString(1).trim()); } rs.close(); stmt.close(); db.close(); } catch (SQLException e) { System.err.println("Invalid SQL in addstudent: " + e.getMessage()); throw new InvalidDBRequestException("???"); } catch (ClassNotFoundException e) { System.err.println("Driver Not Loaded"); throw new InvalidDBRequestException("Internal Server Error"); } }
protected void executeQuery(Statement stmt, String q) throws SQLException { q = q.replace("$PREFIX", getPrefix()); LOG.info(" Executing " + q); ResultSet rs = stmt.executeQuery(q); StringBuilder header = new StringBuilder(); for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++) { if (i > 1) { header.append("|"); } header.append(rs.getMetaData().getColumnName(i)); } LOG.info(header); int seq = 0; while (true) { boolean valid = rs.next(); if (!valid) break; seq++; StringBuilder line = new StringBuilder(); for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++) { if (i > 1) { line.append("|"); } line.append(rs.getString(i)); } LOG.info(seq + ":" + line); } }
/** * Obtains information on a quiz that a student has taken, which includes the student's answer to * the quiz, a unique id of the instance, number of questions in the quiz, number of questions * answered correctly, and vizualisation type of the quiz. Throws InvalidDBRequestException if * cannot find the record of the stuent taking the quiz, quiz is not registered in the database, * or if any error occured to the database connection. * * @param student student's user name * @param quiz quiz name * @param startTime the time the student started the quiz * @return a string tokenizer containing: answer,uniqueID, numQuestions, numCorrect, and * visualType. It uses "@" as the delimiter. * @throws InvalidDBRequestException */ public StringTokenizer getAnswerAndVisualType(String student, String quiz, String startTime) throws InvalidDBRequestException { String answer; String uniqueID; String numQuestions; String numCorrect; String visualType; try { Connection db; Class.forName(GaigsServer.DBDRIVER); db = DriverManager.getConnection(GaigsServer.DBURL, GaigsServer.DBLOGIN, GaigsServer.DBPASSWD); Statement stmt = db.createStatement(); ResultSet rs; // get student's answer, unique id, number of questions, and number of questions answered // correctly rs = stmt.executeQuery( "select transcript, unique_id, num_questions, num_correct from scores " + "where test_name = '" + quiz + "' and user_login = '******' and start_time = '" + startTime + "'"); if (!rs.next()) throw new InvalidDBRequestException("Student has not taken the quiz"); else { answer = rs.getString(1).trim(); uniqueID = rs.getString(2).trim(); numQuestions = rs.getString(3).trim(); numCorrect = rs.getString(4).trim(); } // get quiz vizualisation type rs = stmt.executeQuery("select visual_type from test where name = '" + quiz + "' "); if (!rs.next()) throw new InvalidDBRequestException( "Quiz was not found! Can't retrieve visualization type."); else { visualType = rs.getString(1); } rs.close(); stmt.close(); db.close(); } catch (SQLException e) { System.err.println("Invalid SQL in getAnswerAndVisualType: " + e.getMessage()); throw new InvalidDBRequestException("???"); } catch (ClassNotFoundException e) { System.err.println("Driver Not Loaded"); throw new InvalidDBRequestException("Internal Server Error"); } return new StringTokenizer( answer + "@" + uniqueID + "@" + numQuestions + "@" + numCorrect + "@" + visualType, "@"); }
/** private method which actually will do all of our work for the sample */ private void executeSample() { String query = "select anEmployee from staff2"; try { Statement stmt = _con.createStatement(); ; // Execute the query which will return an Employee object // We will cast this using the Person interface. Note the // Person interface class MUST be in your CLASSPATH. You // Do not need Employee in your CLASSPATH. ResultSet rs = stmt.executeQuery(query); output("***Using interface class\n"); while (rs.next()) { Person aPerson = (Person) rs.getObject(1); displayMethods(aPerson.getClass()); output( "The person is: " + aPerson.toString() + "\nFirst Name= " + aPerson.getFirstName() + "\nLast Name= " + aPerson.getLastName() + "\n"); } // Now execute the same query, but this time we will use // reflection to access the class. Again, only the interface // Person is required in the CLASSPATH rs = stmt.executeQuery(query); output("***Using reflection\n"); Object theObj = null; while (rs.next()) { theObj = rs.getObject(1); output("The person is: " + theObj.toString() + "\n"); Class theClass = theObj.getClass(); displayMethods(theClass); Method m1 = theClass.getMethod("toString", new Class[0]); Method m2 = theClass.getMethod("getFirstName", new Class[0]); Method m3 = theClass.getMethod("getLastName", new Class[0]); output( "The person is: " + (Object) m1.invoke(theObj, new Object[0]) + "\nFirst Name= " + (Object) m2.invoke(theObj, new Object[0]) + "\nLast Name= " + (Object) m3.invoke(theObj, new Object[0]) + "\n"); } rs.close(); stmt.close(); } catch (SQLException sqe) { displaySQLEx(sqe); } catch (Exception e) { error("Unexpected exception : " + e.toString() + "\n"); e.printStackTrace(); } }
/** * Query a quiz list from the database. If there is no student user name specified, the list will * contain all quizzes that are used in the instructor's courses. Otherwise, the list will contain * all quizzes that the student has taken and from the instructor's courses which the student is * registered. Throws InvalidDBRequestException if any error occured to the database connection. * * @param instructor instructor's user name * @param student student's user name. Can be empty to get a list of all quizzes in the * instructor's courses. * @return a vector containing the list of quizzes * @throws InvalidDBRequestException */ public Vector getQuizList(String instructor, String student) throws InvalidDBRequestException { Vector list = new Vector(); try { Connection db; Class.forName(GaigsServer.DBDRIVER); db = DriverManager.getConnection(GaigsServer.DBURL, GaigsServer.DBLOGIN, GaigsServer.DBPASSWD); Statement stmt = db.createStatement(); ResultSet rs; if (!student.equals("")) { // get the list that contains all quizzes that the student has taken and from the // instructor's courses which the student is registered rs = stmt.executeQuery( "select courseTest.test_name, scores.start_time from scores, courseTest, course " + "where courseTest.test_name = scores.test_name " + "and courseTest.course_id = course.course_id " + "and instructor = '" + instructor + "' and user_login = '******' " + "order by scores.start_time"); while (rs.next()) { list.add(rs.getString(1) + " <" + rs.getString(2) + ">"); } } else { // get the list that contains all quizzes that are used in the instructor's courses rs = stmt.executeQuery( "select test_name from courseTest, course " + "where courseTest.course_id = course.course_id " + "and instructor = '" + instructor + "' "); while (rs.next()) { list.add(rs.getString(1)); } } rs.close(); stmt.close(); db.close(); } catch (SQLException e) { System.err.println("Invalid SQL in getQuizList: " + e.getMessage()); throw new InvalidDBRequestException("???"); } catch (ClassNotFoundException e) { System.err.println("Driver Not Loaded"); throw new InvalidDBRequestException("Internal Server Error"); } return list; }
public ExptLocatorTree(Genome g) { super(); try { java.sql.Connection c = DatabaseFactory.getConnection(ExptLocator.dbRole); int species = g.getSpeciesDBID(); int genome = g.getDBID(); Statement s = c.createStatement(); ResultSet rs = null; rs = s.executeQuery( "select e.name, e.version from experiment e, exptToGenome eg where e.active=1 and " + "e.id=eg.experiment and eg.genome=" + genome); while (rs.next()) { String name = rs.getString(1); String version = rs.getString(2); ChipChipLocator loc = new ChipChipLocator(g, name, version); this.addElement(loc.getTreeAddr(), loc); } rs.close(); rs = s.executeQuery( "select ra.name, ra.version from rosettaanalysis ra, rosettaToGenome rg where " + "ra.id = rg.analysis and ra.active=1 and rg.genome=" + genome); while (rs.next()) { String name = rs.getString(1); String version = rs.getString(2); MSPLocator msp = new MSPLocator(g, name, version); this.addElement(msp.getTreeAddr(), msp); } rs.close(); rs = s.executeQuery( "select ra.name, ra.version from bayesanalysis ra, bayesToGenome rg where " + "ra.id = rg.analysis and ra.active=1 and rg.genome=" + genome); while (rs.next()) { String name2 = rs.getString(1); String version2 = rs.getString(2); ExptLocator loc2 = new BayesLocator(g, name2, version2); addElement(loc2.getTreeAddr(), loc2); } rs.close(); s.close(); DatabaseFactory.freeConnection(c); } catch (SQLException se) { se.printStackTrace(System.err); throw new RuntimeException(se); } catch (UnknownRoleException e) { e.printStackTrace(); } }
public void ramasserObjet() { boolean vide = true; try { ResultSet rset = stmt.executeQuery( "select idObjet from objet where positionX=" + positionX + " and positionY=" + positionY); Hashtable<String, String> tabObj = new Hashtable<String, String>(); while (rset.next()) { vide = false; String idObj = rset.getString("idObjet"); System.out.println(idObj); tabObj.put(idObj, idObj); } rset.close(); if (!vide) { System.out.println("Quel objet voulez vous ramasser ? : "); String obj = IO.lireChaine(); if (tabObj.containsKey(obj)) { proc = conn.prepareCall("{call rammasser(?,?)}"); proc.setInt(1, idTroll); proc.setString(2, obj); proc.executeUpdate(); proc.close(); rset = stmt.executeQuery("select typeObjet from objet where idObjet='" + obj + "'"); rset.first(); String type = rset.getString("typeObjet"); if (type.equals("potion")) { menu.supprimerPopo(obj); } else { menu.supprimerObjet(obj); } rset = stmt.executeQuery("select paRestants from troll where idTroll=" + idTroll); int ancVal = 0; while (rset.next()) { ancVal = rset.getInt("paRestants"); } stmt.executeUpdate( "update troll SET paRestants = " + (ancVal - 1) + " where idTroll=" + idTroll); paRestants = paRestants - 1; } else { System.out.println("Cet objet ne se trouve pas sur votre case !"); } } else { System.out.println("Il n'y a aucun objet sur votre case"); } } catch (SQLException E) { System.err.println("SQLException: " + E.getMessage()); System.err.println("SQLState: " + E.getSQLState()); } }
void processNewUser(NewUserMessage message) { String newUsername = this.validateUsername(message.getUsername()); NewUserMessage uMessage = new NewUserMessage(newUsername); try { session.getBasicRemote().sendObject(uMessage); } catch (IOException | EncodeException ioe) { System.out.println( "Error signing " + message.getUsername() + " into chat : " + ioe.getMessage()); } this.registerUser(newUsername); try { ResultSet rs = null, ds = null; String z, x; String url1 = "jdbc:mysql://localhost:3306/chat"; Connection conn1 = DriverManager.getConnection(url1, "root", "root"); Statement st1 = conn1.createStatement(); Statement st2 = conn1.createStatement(); String myQuery = "SELECT Message,Recepient FROM Log WHERE User = '******'"; System.out.println(myQuery); rs = st1.executeQuery("SELECT Message,Recepient FROM Log WHERE User = '******';"); while (rs.next()) { z = rs.getString("Message"); x = rs.getString("Recepient"); ChatUpdateMessage cdm1 = new ChatUpdateMessage(newUsername, z, x); try { session.getBasicRemote().sendObject(cdm1); } catch (IOException | EncodeException ex) { System.out.println("Error updating a client : " + ex.getMessage()); } } ds = st2.executeQuery("SELECT Message,User FROM Log WHERE Recepient = '" + newUsername + "';"); while (ds.next()) { z = ds.getString("Message"); x = ds.getString("User"); ChatUpdateMessage cdm2 = new ChatUpdateMessage(x, z, newUsername); try { session.getBasicRemote().sendObject(cdm2); } catch (IOException | EncodeException ex) { System.out.println("Error updating a client : " + ex.getMessage()); } } } catch (Exception e) { System.err.println("Got an exception! "); System.err.println(e.getMessage()); } this.broadcastUserListUpdate(); }
/** * This will look through the completed_txn_components table and look for partitions or tables * that may be ready for compaction. Also, look through txns and txn_components tables for aborted * transactions that we should add to the list. * * @param maxAborted Maximum number of aborted queries to allow before marking this as a potential * compaction. * @return list of CompactionInfo structs. These will not have id, type, or runAs set since these * are only potential compactions not actual ones. */ public Set<CompactionInfo> findPotentialCompactions(int maxAborted) throws MetaException { Connection dbConn = getDbConn(); Set<CompactionInfo> response = new HashSet<CompactionInfo>(); try { Statement stmt = dbConn.createStatement(); // Check for completed transactions String s = "select distinct ctc_database, ctc_table, " + "ctc_partition from COMPLETED_TXN_COMPONENTS"; LOG.debug("Going to execute query <" + s + ">"); ResultSet rs = stmt.executeQuery(s); while (rs.next()) { CompactionInfo info = new CompactionInfo(); info.dbname = rs.getString(1); info.tableName = rs.getString(2); info.partName = rs.getString(3); response.add(info); } // Check for aborted txns s = "select tc_database, tc_table, tc_partition " + "from TXNS, TXN_COMPONENTS " + "where txn_id = tc_txnid and txn_state = '" + TXN_ABORTED + "' " + "group by tc_database, tc_table, tc_partition " + "having count(*) > " + maxAborted; LOG.debug("Going to execute query <" + s + ">"); rs = stmt.executeQuery(s); while (rs.next()) { CompactionInfo info = new CompactionInfo(); info.dbname = rs.getString(1); info.tableName = rs.getString(2); info.partName = rs.getString(3); info.tooManyAborts = true; response.add(info); } LOG.debug("Going to rollback"); dbConn.rollback(); } catch (SQLException e) { LOG.error("Unable to connect to transaction database " + e.getMessage()); } finally { closeDbConn(dbConn); } return response; }
private void getIgnoreList() { Connection con = null; try { con = pool.getConnection(timeout); Statement s = con.createStatement(); s.executeQuery("SELECT `name`, `type` FROM `ignores`"); ResultSet rs = s.getResultSet(); this.ignore_list.clear(); this.soft_ignore_list.clear(); while (rs.next()) { if (rs.getString("type").equals("hard")) { this.ignore_list.add(rs.getString("name").toLowerCase()); } else { this.soft_ignore_list.add(rs.getString("name").toLowerCase()); } } rs.close(); s.close(); } catch (SQLException ex) { Logger.getLogger(DBAccess.class.getName()).log(Level.SEVERE, null, ex); } finally { try { if (con != null) { con.close(); } } catch (SQLException ex) { Logger.getLogger(DBAccess.class.getName()).log(Level.SEVERE, null, ex); } } }
private void getPokemon() { Connection con = null; try { con = pool.getConnection(timeout); try (Statement s = con.createStatement()) { ResultSet rs; s.executeQuery("SELECT `name` FROM `pokemon`"); rs = s.getResultSet(); this.pokemon.clear(); while (rs.next()) { this.pokemon.add(rs.getString("name")); } rs.close(); s.close(); } } catch (SQLException ex) { Logger.getLogger(DBAccess.class.getName()).log(Level.SEVERE, null, ex); } finally { try { if (con != null) { con.close(); } } catch (SQLException ex) { Logger.getLogger(DBAccess.class.getName()).log(Level.SEVERE, null, ex); } } }
@SuppressWarnings("unchecked") @Test public void testFindCustomersWithConnection() throws Exception { CustomerDAO dao = EasyMock.createMockBuilder(CustomerDAO.class) .addMockedMethod("readNextCustomer") .addMockedMethod("getCustomerQuery") .createStrictMock(); ResultSet resultSet = EasyMock.createStrictMock(ResultSet.class); Connection connection = EasyMock.createStrictMock(Connection.class); Statement statement = EasyMock.createStrictMock(Statement.class); List<SearchConstraint> constraints = new LinkedList<SearchConstraint>(); EasyMock.expect(dao.getCustomerQuery(constraints)).andReturn("aQuery"); EasyMock.expect(connection.createStatement()).andReturn(statement); EasyMock.expect(statement.executeQuery("aQuery")).andReturn(resultSet); EasyMock.expect(resultSet.next()).andReturn(true); EasyMock.expect(dao.readNextCustomer(EasyMock.eq(resultSet), EasyMock.isA(List.class))) .andReturn(true); EasyMock.expect(dao.readNextCustomer(EasyMock.eq(resultSet), EasyMock.isA(List.class))) .andReturn(true); EasyMock.expect(dao.readNextCustomer(EasyMock.eq(resultSet), EasyMock.isA(List.class))) .andReturn(false); resultSet.close(); EasyMock.expectLastCall(); statement.close(); }
/** * This method queries the database to get the sequence for the BP_ID. * * @exception SQLException, if query fails * @author */ public String getBpid() { String query; String bpid = ""; Statement stmt = null; ResultSet rs = null; query = "select bp_id_seq.nextval from dual "; try { stmt = conn.createStatement(); rs = stmt.executeQuery(query); if (rs.next()) { bpid = rs.getString(1); } if (rs != null) rs.close(); if (stmt != null) stmt.close(); } catch (SQLException ex) { USFEnv.getLog().writeCrit("Dinvjrnl: Sequence Value for BP_ID not Retreived ", this, ex); try { if (rs != null) rs.close(); if (stmt != null) stmt.close(); } catch (SQLException e) { USFEnv.getLog().writeCrit("Unable to close the resultset/statement", this, e); } } return bpid; }
/** * Deletes an instructor from the database. Deletes the instructor's courses by invoking the * deleteCourse method. Throws InvalidDBRequestException if instructor not in the database or * other database connection problems. * * @see deleteCourse * @param instructor instructor's user name * @throws InvalidDBRequestException */ public void deleteInstructor(String instructor) throws InvalidDBRequestException { try { Class.forName(GaigsServer.DBDRIVER); db = DriverManager.getConnection(GaigsServer.DBURL, GaigsServer.DBLOGIN, GaigsServer.DBPASSWD); Statement stmt = db.createStatement(); int count; // delete the instructor's courses ResultSet rs = stmt.executeQuery( "select course_num from course where instructor = '" + instructor + "'"); while (rs.next()) deleteCourse(rs.getString(1).trim(), instructor); // delete the instructor's record count = stmt.executeUpdate("delete from instructor where login ='******'"); rs.close(); stmt.close(); db.close(); } catch (SQLException e) { System.err.println("Invalid SQL in addCourse: " + e.getMessage()); throw new InvalidDBRequestException("??? "); } catch (ClassNotFoundException e) { System.err.println("Driver Not Loaded"); throw new InvalidDBRequestException("Internal Server Error"); } }
/** * Deletes students who are older than a certain number of years and not registered to any course. * * @param year students older than year are candidates to be deleted * @throws InvalidDBRequestException */ public void deleteOldStudent(int year) throws InvalidDBRequestException { try { Class.forName(GaigsServer.DBDRIVER); db = DriverManager.getConnection(GaigsServer.DBURL, GaigsServer.DBLOGIN, GaigsServer.DBPASSWD); Statement stmt = db.createStatement(); // query all student who have been in the database longer than a number of years and not // registered to any course ResultSet rs = stmt.executeQuery( "select login, count(course_id) " + "from student s left join courseRoster r on login = user_login " + "where date_entered < SUBDATE(now(), INTERVAL " + new String().valueOf(year).trim() + " YEAR) " + "group by login, date_entered"); // delete them while (rs.next()) if (rs.getInt(2) == 0) purgeStudent(rs.getString(1).trim()); rs.close(); stmt.close(); db.close(); } catch (SQLException e) { System.err.println("Invalid SQL in addCourse: " + e.getMessage()); throw new InvalidDBRequestException("??? "); } catch (ClassNotFoundException e) { System.err.println("Driver Not Loaded"); throw new InvalidDBRequestException("Internal Server Error"); } }
public static void customStartAll(Connection conn) throws SQLException { String method = "customStartAll"; int location = 1000; try { Statement stmt = conn.createStatement(); int id = 0; int gpfdistPort = 0; String strSQL = "SELECT id\n"; strSQL += "FROM os.custom_sql"; ResultSet rs = stmt.executeQuery(strSQL); while (rs.next()) { id = rs.getInt(1); gpfdistPort = GpfdistRunner.customStart(OSProperties.osHome); strSQL = "INSERT INTO os.ao_custom_sql\n"; strSQL += "(id, table_name, columns, column_datatypes, sql_text, source_type, source_server_name, source_instance_name, source_port, source_database_name, source_user_name, source_pass, gpfdist_port)\n"; strSQL += "SELECT id, table_name, columns, column_datatypes, sql_text, source_type, source_server_name, source_instance_name, source_port, source_database_name, source_user_name, source_pass, " + gpfdistPort + "\n"; strSQL += "FROM os.custom_sql\n"; strSQL += "WHERE id = " + id; stmt.executeUpdate(strSQL); } } catch (SQLException ex) { throw new SQLException( "(" + myclass + ":" + method + ":" + location + ":" + ex.getMessage() + ")"); } }
/** * Gets a list of courses that belongs to an instructor. Throws InvalidDBRequestException if any * error occured to the database connection. * * @param name the instructor's user name * @return a vector containing the list of courses * @throws InvalidDBRequestException */ public Vector getCourseList(String name) throws InvalidDBRequestException { Vector courseList = new Vector(); try { Connection db; Class.forName(GaigsServer.DBDRIVER); db = DriverManager.getConnection(GaigsServer.DBURL, GaigsServer.DBLOGIN, GaigsServer.DBPASSWD); Statement stmt = db.createStatement(); ResultSet rs; // get the course list rs = stmt.executeQuery( "select course_num, course_name from course where instructor = '" + name + "' order by course_num"); while (rs.next()) courseList.add(rs.getString(1) + " - " + rs.getString(2)); rs.close(); stmt.close(); db.close(); } catch (SQLException e) { System.err.println("Invalid SQL in getCourseList: " + e.getMessage()); throw new InvalidDBRequestException("???"); } catch (ClassNotFoundException e) { System.err.println("Driver Not Loaded"); throw new InvalidDBRequestException("Server Error"); } return courseList; }
/** * Get organisation's name sequence * * @param iOrgID * @return * @throws SQLException * @throws Exception * @author Maruli */ public int getNameSeq(int iOrgID) throws SQLException, Exception { String query = "SELECT NameSequence FROM tblOrganization WHERE PKOrganization =" + iOrgID; int iNameSeqe = 0; Connection con = null; Statement st = null; ResultSet rs = null; try { con = ConnectionBean.getConnection(); st = con.createStatement(); rs = st.executeQuery(query); if (rs.next()) { iNameSeqe = rs.getInt(1); } } catch (Exception E) { System.err.println("Organization.java - getNameSeq - " + E); } finally { ConnectionBean.closeRset(rs); // Close ResultSet ConnectionBean.closeStmt(st); // Close statement ConnectionBean.close(con); // Close connection } return iNameSeqe; }
/** Get Organisation ID by User email */ public int getOrgIDbyEmail(String UserEmail) throws SQLException, Exception { String query = "Select COUNT(*) as TotRecord from tblEmail"; int count = 0; Connection con = null; Statement st = null; ResultSet rs = null; try { con = ConnectionBean.getConnection(); st = con.createStatement(); rs = st.executeQuery(query); if (rs.next()) { count = rs.getInt(1); } } catch (Exception E) { System.err.println("Organization.java - editRecord - " + E); } finally { ConnectionBean.closeRset(rs); // Close ResultSet ConnectionBean.closeStmt(st); // Close statement ConnectionBean.close(con); // Close connection } return count; }
public String getOrganisationName(int iFKOrg) { String sOrgName = ""; String querySql = "SELECT * FROM tblOrganization WHERE PKOrganization = " + iFKOrg; Connection con = null; Statement st = null; ResultSet rs = null; try { con = ConnectionBean.getConnection(); st = con.createStatement(); rs = st.executeQuery(querySql); if (rs.next()) sOrgName = rs.getString("OrganizationName"); } catch (Exception E) { System.err.println("Organization.java - getOrganizationName - " + E); } finally { ConnectionBean.closeRset(rs); // Close ResultSet ConnectionBean.closeStmt(st); // Close statement ConnectionBean.close(con); // Close connection } return sOrgName; }
/* Method Name : isConsulting * Checks whether login organisation is a Consulting Company * @param sOrgName * @param orgCode * @author Mark Oei * @since v.1.3.12.63 (09 Mar 2010) */ public boolean isConsulting(String orgName) { String sOrgName = ""; orgName = "\'" + orgName + "\'"; String querySql = "SELECT * FROM tblConsultingCompany WHERE CompanyName = " + orgName; // Change to disable print statement. Used for debugging only // Mark Oei 19 Mar 2010 // System.out.println("testing " + orgName); Connection con = null; Statement st = null; ResultSet rs = null; try { con = ConnectionBean.getConnection(); st = con.createStatement(); rs = st.executeQuery(querySql); if (rs.next()) sOrgName = rs.getString("CompanyName"); } catch (Exception E) { System.err.println("Organization.java - isConsulting - " + E); } finally { ConnectionBean.closeRset(rs); // Close ResultSet ConnectionBean.closeStmt(st); // Close statement ConnectionBean.close(con); // Close connection } // Change to disable print statement. Used for debugging only // Mark Oei 19 Mar 2010 // System.out.println("testing " + sOrgName); if ((sOrgName == null) || (sOrgName == "")) return false; else return true; } // End of isConsulting
public Connection getConnection() throws SQLException { synchronized (pool) { if (!pool.isEmpty()) { int last = pool.size() - 1; Connection pooled = (Connection) pool.remove(last); boolean conn_ok = true; String test_table = prop.getProperty("test_table"); if (test_table != null) { Statement stmt = null; try { stmt = pooled.createStatement(); stmt.executeQuery("select * from " + prop.getProperty("test_table")); } catch (SQLException ex) { conn_ok = false; // 连接不可用 } finally { if (stmt != null) { stmt.close(); } } } if (conn_ok == true) { return pooled; } else { pooled.close(); } } } Connection conn = DriverManager.getConnection( prop.getProperty("url"), prop.getProperty("username"), prop.getProperty("password")); return conn; }
/** * Get Company ID by OrganisationID * * @param OrgID * @return PKCompany * @throws SQLException * @throws Exception */ public int getCompanyID(int OrgID) throws SQLException, Exception { String query = "Select FKCompanyID from tblOrganization WHERE PKOrganization = " + OrgID; /*db.openDB(); Statement stmt = db.con.createStatement(); ResultSet rs = stmt.executeQuery(query); if(rs.next()) return rs.getInt(1);*/ int iCompanyID = 0; Connection con = null; Statement st = null; ResultSet rs = null; try { con = ConnectionBean.getConnection(); st = con.createStatement(); rs = st.executeQuery(query); if (rs.next()) { iCompanyID = rs.getInt(1); } } catch (Exception E) { System.err.println("Organization.java - getCompanyID - " + E); } finally { ConnectionBean.closeRset(rs); // Close ResultSet ConnectionBean.closeStmt(st); // Close statement ConnectionBean.close(con); // Close connection } return iCompanyID; }
public static String getVersion(Connection conn) throws SQLException { String method = "getVersion"; int location = 1000; try { location = 2000; String value = ""; location = 2100; Statement stmt = conn.createStatement(); String strSQL = "SELECT CASE " + "WHEN POSITION ('HAWQ 2.0.1' in version) > 0 THEN 'HAWQ_2_0_1' " + "WHEN POSITION ('HAWQ 2.0.0' in version) > 0 THEN 'HAWQ_2_0_0' " + "WHEN POSITION ('HAWQ 1' in version) > 0 THEN 'HAWQ_1' " + "WHEN POSITION ('HAWQ' in version) = 0 AND POSITION ('Greenplum Database' IN version) > 0 THEN 'GPDB' " + "ELSE 'OTHER' END " + "FROM version()"; if (debug) Logger.printMsg("Getting Variable: " + strSQL); location = 2200; ResultSet rs = stmt.executeQuery(strSQL); while (rs.next()) { value = rs.getString(1); } location = 2300; return value; } catch (SQLException ex) { throw new SQLException( "(" + myclass + ":" + method + ":" + location + ":" + ex.getMessage() + ")"); } }
/** * Get organisation's nomination rater status * * @param iOrgID * @return * @throws SQLException * @throws Exception * @author Desmond */ public boolean getNomRater(int iOrgID) throws SQLException, Exception { String query = "SELECT NominationModule FROM tblOrganization WHERE PKOrganization =" + iOrgID; boolean iNomRater = true; Connection con = null; Statement st = null; ResultSet rs = null; try { con = ConnectionBean.getConnection(); st = con.createStatement(); rs = st.executeQuery(query); if (rs.next()) { iNomRater = rs.getBoolean(1); } } catch (Exception E) { System.err.println("Organization.java - getNomRater - " + E); } finally { ConnectionBean.closeRset(rs); // Close ResultSet ConnectionBean.closeStmt(st); // Close statement ConnectionBean.close(con); // Close connection } return iNomRater; } // End getNomRater()
public static String getVariable(Connection conn, String name) throws SQLException { String method = "getVariable"; int location = 1000; try { location = 2000; String value = ""; location = 2100; Statement stmt = conn.createStatement(); String strSQL = "SELECT os.fn_get_variable('" + name + "')"; if (debug) Logger.printMsg("Getting Variable: " + strSQL); location = 2200; ResultSet rs = stmt.executeQuery(strSQL); while (rs.next()) { value = rs.getString(1); } location = 2300; return value; } catch (SQLException ex) { throw new SQLException( "(" + myclass + ":" + method + ":" + location + ":" + ex.getMessage() + ")"); } }