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); } }
/** * Tests the implementation of getCharacterStream(long pos, long length). * * @throws Exception */ public void testGetCharacterStreamLong() throws Exception { String str1 = "This is a test String. This is a test String"; Reader r1 = new java.io.StringReader(str1); PreparedStatement ps = prepareStatement("insert into BLOBCLOB(ID, CLOBDATA) values(?,?)"); int id = BlobClobTestSetup.getID(); ps.setInt(1, id); ps.setCharacterStream(2, r1); ps.execute(); ps.close(); Statement st = createStatement(); ResultSet rs = st.executeQuery("select CLOBDATA from " + "BLOBCLOB where ID=" + id); rs.next(); Clob clob = rs.getClob(1); Reader r_1 = clob.getCharacterStream(2L, 5L); String str2 = str1.substring(1, 6); Reader r_2 = new java.io.StringReader(str2); assertEquals(r_2, r_1); rs.close(); st.close(); }
/** * 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"); } }
public void updateOptionPrice( String modelName, String optionSetName, String optionName, float newPrice) { try { int autoid = 0; String sql = "select id from automobile where name ='" + modelName + "';"; ResultSet rs = statement.executeQuery(sql); while (rs.next()) { autoid = rs.getInt("id"); // get auto_id } int opsid = 0; sql = "select id from optionset where name ='" + optionSetName + "' and auto_id= " + autoid + ";"; rs = statement.executeQuery(sql); while (rs.next()) { opsid = rs.getInt("id"); // get option_id } sql = "update options set price = " + newPrice + " where name= '" + optionName + "' and option_id= " + opsid + ";"; statement.executeUpdate(sql); // update it with name and option_id } catch (SQLException e) { e.printStackTrace(); } }
public void deleteOption(String modelName, String optionSetName, String option) { try { int autoid = 0; String sql = "select id from automobile where name ='" + modelName + "';"; ResultSet rs; rs = statement.executeQuery(sql); while (rs.next()) { autoid = rs.getInt("id"); // get auto_id } int opsid = 0; sql = "select id from optionset where name ='" + optionSetName + "' and auto_id= " + autoid + ";"; rs = statement.executeQuery(sql); while (rs.next()) { opsid = rs.getInt("id"); // get option_id } sql = "delete from options where name= '" + option + "' and option_id= " + opsid; statement.executeUpdate(sql); // delete it using name and option_id } catch (SQLException e) { e.printStackTrace(); } }
public void actionPerformed(ActionEvent ae) { try { if (ae.getSource() == b7) { rs = st.executeQuery("select count(*) from employeemaster"); if (rs.next()) { t6.setText(rs.getString(1)); } rs = st.executeQuery("select * from Head"); if (rs.next()) { t1.setText(rs.getString(1)); t2.setText(rs.getString(2)); t7.setText(rs.getString(3)); t4.setText(rs.getString(4)); t5.setText(rs.getString(5)); t3.setText(rs.getString(6)); } } else if (ae.getSource() == b6) { dispose(); } } catch (Exception e) { JOptionPane.showMessageDialog(this, "Error is" + e); } }
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); } }
/** 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(); } }
/** * 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, "@"); }
/** * 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(); } }
/* * addAuto method. parse the Automobile object and add them to three tables. */ public void addAuto(Automobile auto) { String name = null; float price = 0; int autoid = 0; String sql = null; try { String autoName = auto.getMake() + " " + auto.getModel(); price = auto.getBasePrice(); sql = "insert into automobile (name, base_price) values('" + autoName + "'," + price + ")"; // MySQL command statement.executeUpdate(sql); // add to automobile table sql = "select id from automobile where name ='" + autoName + "';"; ResultSet rs = statement.executeQuery(sql); // use ResultSet object to receive while (rs.next()) { autoid = rs.getInt("id"); // get auto_id } for (int i = 0; i < auto.getOptionSetNum(); i++) { name = auto.getOptionSetName(i); sql = "insert into optionset (name, auto_id) values('" + name + "'," + autoid + ")"; statement.executeUpdate(sql); // add to optionset table int opsid = 0; sql = "select id from optionset where name ='" + name + "';"; ResultSet rrs = statement.executeQuery(sql); while (rrs.next()) { opsid = rrs.getInt("id"); // get optionset id } for (int j = 0; j < auto.getOptionNum(i); j++) { name = auto.getOptionName(i, j); price = auto.getOptionPrice(i, j); sql = "insert into options (name, price, option_id) values('" + name + "'," + price + "," + opsid + ")"; statement.executeUpdate(sql); // add to options table } } } catch (SQLException e) { e.printStackTrace(); } }
public static void duration() { connectDb(); String sql = "select min(time), max(time), count(*) from " + tablename + ";"; try { ResultSet rs = query.executeQuery(sql); rs.next(); int numCols = rs.getMetaData().getColumnCount(); String minTime = rs.getString(1); String maxTime = rs.getString(2); String numPackets = rs.getString(3); System.out.println( "Experiment " + tablename + "\n\tfrom: " + minTime + "\n\tto: " + maxTime + "\n\tpackets: " + numPackets); } catch (SQLException e) { System.out.println("SQL Exception: " + e); System.exit(1); } }
/** * 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; }
private static void addCourse(Connection conn, String stu_no) throws SQLException { String cno = readEntry("Course number : "); String sno = readEntry("Section number : "); String course_query = "SELECT Section_identifier FROM SECTION WHERE Section_identifier=" + sno + " AND Course_number='" + cno + "' AND Semester='Spring' AND YEAR=TO_DATE('2007','YYYY')"; // System.out.println(course_query); Statement s1 = conn.createStatement(); ResultSet r1 = s1.executeQuery(course_query); if (r1.next()) { String addc = "INSERT INTO GRADE_REPORT (Student_number, Section_identifier, Grade) VALUES (" + stu_no + ", " + sno + ", 'NULL')"; Statement s2 = conn.createStatement(); System.out.println(addc); try { s2.executeUpdate(addc); System.out.println("Enrollment successfull"); } catch (SQLException e) { System.out.println("Cannot add course into table"); } } else { System.out.println("Course not found"); } s1.close(); }
private static void dropCourse(Connection conn, String stu_no) throws SQLException { String cno = readEntry("Course number: "); String sno = readEntry("Section number : "); String chks = "SELECT g.Section_identifier FROM SECTION s, GRADE_REPORT g where s.Section_identifier=g.Section_identifier AND s.Course_number='" + cno + "' AND g.Section_identifier=" + sno + " AND s.Semester='Spring' AND s.Year=TO_DATE('2007','YYYY') AND g.Student_number=" + stu_no; Statement s3 = conn.createStatement(); ResultSet r3 = s3.executeQuery(chks); if (r3.next()) { String del = "DELETE FROM GRADE_REPORT WHERE Student_number=" + stu_no + " AND Section_identifier=" + sno; Statement s4 = conn.createStatement(); try { s4.executeUpdate(del); System.out.println("Course dropped"); } catch (SQLException e) { System.out.println("Cannot drop a course from table"); } } else { System.out.println("Enrollment data not found. Check the input and try again."); } }
private synchronized void init() throws SQLException { if (isClosed) return; // do tables exists? Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(TABLE_NAMES_SELECT_STMT); ArrayList<String> missingTables = new ArrayList(TABLES.keySet()); while (rs.next()) { String tableName = rs.getString("name"); missingTables.remove(tableName); } for (String missingTable : missingTables) { try { Statement createStmt = conn.createStatement(); // System.out.println("Adding table "+ missingTable); createStmt.executeUpdate(TABLES.get(missingTable)); createStmt.close(); } catch (Exception e) { System.err.println(e.getClass().getName() + ": " + e.getMessage()); } } }
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() + ")"); } }
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() + ")"); } }
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() + ")"); } }
public void setQuery(String q) { cache = new Vector(); try { ResultSet rs = statement.executeQuery(q); ResultSetMetaData meta = rs.getMetaData(); colCount = meta.getColumnCount(); headers = new String[colCount]; for (int h = 1; h <= colCount; h++) { headers[h - 1] = meta.getColumnName(h); } while (rs.next()) { String[] record = new String[colCount]; for (int i = 0; i < colCount; i++) { record[i] = rs.getString(i + 1); } cache.addElement(record); } // while sonu fireTableChanged(null); } // try sonu catch (Exception e) { cache = new Vector(); e.printStackTrace(); } } // setQuery sonu
/** * Test that <code>Clob.getCharacterStream(long,long)</code> works on CLOBs that are streamed from * store. (DERBY-2891) */ public void testGetCharacterStreamLongOnLargeClob() throws Exception { getConnection().setAutoCommit(false); // create large (>32k) clob that can be read from store final int size = 33000; StringBuilder sb = new StringBuilder(size); for (int i = 0; i < size; i += 10) { sb.append("1234567890"); } final int id = BlobClobTestSetup.getID(); PreparedStatement ps = prepareStatement("insert into blobclob(id, clobdata) values (?,cast(? as clob))"); ps.setInt(1, id); ps.setString(2, sb.toString()); ps.executeUpdate(); ps.close(); Statement s = createStatement(); ResultSet rs = s.executeQuery("select clobdata from blobclob where id = " + id); assertTrue(rs.next()); Clob c = rs.getClob(1); // request a small region of the clob BufferedReader r = new BufferedReader(c.getCharacterStream(4L, 3L)); assertEquals("456", r.readLine()); r.close(); c.free(); rs.close(); s.close(); rollback(); }
/** * 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; }
/** * 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 String checkValidLogin(String myUserName, String myPW) { try { Class.forName(javaSQLDriverPath); Connection conn = (Connection) DriverManager.getConnection(ConnectionPath, ConnectionUser, ConnectionPW); Statement st = conn.createStatement(); String query = "Select * from User"; ResultSet rs = st.executeQuery(query); while (rs.next()) { // return rs.getString("Username"); if (myUserName.equals(rs.getString("Username"))) { if (myPW.equals(rs.getString("Password"))) { setUserVariables(myUserName); return "success"; } else { return "wrongPassword"; } } } rs.close(); st.close(); conn.close(); return "userNotFound"; } catch (Exception e) { return e.getMessage(); } }
public List<ClientEventEntry> findLogEvents( List<SearchConstraint> constraints, List<String> orderBy, int offset, int limit, Connection c) throws SQLException { StringBuffer sql = new StringBuffer( "select e.event_id, e.customer_id, e.user_id, e.event_time, e.description, e.has_log_file from dat_client_log_events e "); appendWhere(sql, constraints, s_propToColumnMap); appendOrderBy(sql, orderBy, "e.event_id desc", s_propToColumnMap); appendLimits(sql, offset, limit); Statement stmt = null; ResultSet rs = null; try { stmt = c.createStatement(); rs = stmt.executeQuery(sql.toString()); List<ClientEventEntry> results = new ArrayList<ClientEventEntry>(); while (rs.next()) { ClientEventEntry entry = new ClientEventEntry( rs.getInt(1), rs.getInt(2), rs.getInt(3), resolveDate(rs.getTimestamp(4)), rs.getString(5), rs.getInt(6) != 0); results.add(entry); } return results; } finally { DbUtils.safeClose(rs); DbUtils.safeClose(stmt); } }
/* to search the DB table for req. video*/ boolean search(String file) { boolean found = false; Connection con = null; String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)}; DBQ=D://db.mdb; DriverID=22;READONLY=true;"; try { con = DriverManager.getConnection(url, "", ""); try { Statement st = con.createStatement(); ResultSet rs = st.executeQuery("SELECT video FROM p3"); while (rs.next()) { String colvalue = rs.getString("video"); if (colvalue.equalsIgnoreCase(file)) found = true; } } catch (SQLException s) { System.out.println("SQL statement is not executed!"); } } catch (Exception e) { System.out.println(e); } return found; }
/** * Check the user's name and password and verify that the user is an instructor. Throws * InvalidDBRequestException if user is not an instructor, wrong password, or if any error occured * to the database connection. * * @param name user's user name * @param pass user's password * @throws InvalidDBRequestException */ public void instructorLogin(String name, String pass) throws InvalidDBRequestException { try { Connection db; Class.forName(GaigsServer.DBDRIVER); db = DriverManager.getConnection(GaigsServer.DBURL, GaigsServer.DBLOGIN, GaigsServer.DBPASSWD); Statement stmt = db.createStatement(); ResultSet rs; // check if instructor rs = stmt.executeQuery("select password from instructor where login = '******'"); if (!rs.next()) { if (debug) System.out.println("User not found in the instructor table"); throw new InvalidDBRequestException("Instructor not registered"); } // check password if (!rs.getString(1).equals(pass)) { if (debug) System.out.println("Invalid password for user: "******"Invalid password for user: "******"Invalid SQL in instructor login: "******"???"); } catch (ClassNotFoundException e) { System.err.println("Driver Not Loaded"); throw new InvalidDBRequestException("Server Error"); } }
public List<Empleado> getAllEmpleados() { List ll = new LinkedList(); Statement st; ResultSet rs; String url = "jdbc:mysql://localhost:3306/food"; String user = "******"; String pass = "******"; String driver = "com.mysql.jdbc.Driver"; try (Connection connection = DriverManager.getConnection(url, user, pass)) { Class.forName(driver); st = connection.createStatement(); String recordQuery = ("Select * from empleados"); rs = st.executeQuery(recordQuery); while (rs.next()) { Integer id = rs.getInt("idEmpleados"); String name = rs.getString("Nombre"); String telf = rs.getString("Telefono"); ll.add(new Empleado(id, name, telf)); /// System.out.println(id +","+ name +","+ apellido +","+ cedula +","+ telf +" // "+direccion+""); } } catch (ClassNotFoundException | SQLException ex) { Logger.getLogger(MenuEmpleados.class.getName()).log(Level.SEVERE, null, ex); } return ll; }