// Takes and image_id, pulls in the image from cache, and goes about // encoding it to put it into the database in a transaction. The last // query in the transaction records the image having been stored. protected void storeImage(int image_id) throws Exception { PhotoImage p = new PhotoImage(image_id); SpyDB pdb = getDB(); Connection db = null; Statement st = null; Vector v = p.getImage(); System.err.println( "Storer: Got image for " + image_id + " " + v.size() + " lines of data to store."); try { int i = 0, n = 0; db = pdb.getConn(); db.setAutoCommit(false); st = db.createStatement(); BASE64Encoder base64 = new BASE64Encoder(); String data = ""; for (; i < v.size(); i++) { String tmp = base64.encodeBuffer((byte[]) v.elementAt(i)); tmp = tmp.trim(); if (data.length() < 2048) { data += tmp + "\n"; } else { storeQuery(image_id, n, st, data); data = tmp; n++; } } // OK, this is sick, but another one right now for the spare. if (data.length() > 0) { System.err.println("Storer: Storing spare."); storeQuery(image_id, n, st, data); n++; } System.err.println("Storer: Stored " + n + " lines of data for " + image_id + "."); st.executeUpdate( "update upload_log set stored=datetime(now())\n" + "\twhere photo_id = " + image_id); db.commit(); // Go ahead and generate a thumbnail. p.getThumbnail(); } catch (Exception e) { // If anything happens, roll it back. if (st != null) { try { db.rollback(); } catch (Exception e3) { // Nothing } } } finally { if (db != null) { try { db.setAutoCommit(true); } catch (Exception e) { System.err.println("Error: " + e); } } pdb.freeDBConn(); } }
/** * 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(); }
/** * 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"); } }
/** * Delete a student from the database. Also deletes the student's folders. Throws * InvalidDBRequestException if any error in database connection. * * @param username student's user name * @throws InvalidDBRequestException */ private void purgeStudent(String username) throws InvalidDBRequestException { try { Class.forName(GaigsServer.DBDRIVER); db = DriverManager.getConnection(GaigsServer.DBURL, GaigsServer.DBLOGIN, GaigsServer.DBPASSWD); Statement stmt = db.createStatement(); int count; // delete from scores count = stmt.executeUpdate("delete from scores where user_login = '******'"); // delete from student count = stmt.executeUpdate("delete from student where login = '******'"); // delete student's folder File studentDir = new File("./StudentQuizzes/" + username); if (!(studentDir.delete())) { System.err.println("Error in deleting folder for student: " + username); } 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"); } }
/** * 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 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."); } }
public static void failJobs(Connection conn) throws SQLException { String method = "failJobs"; int location = 1000; try { Statement stmt = conn.createStatement(); String strSQL = "INSERT INTO os.ao_queue (queue_id, status, queue_date, start_date, end_date, " + "error_message, num_rows, id, refresh_type, target_schema_name, target_table_name, target_append_only, " + "target_compressed, target_row_orientation, source_type, source_server_name, source_instance_name, " + "source_port, source_database_name, source_schema_name, source_table_name, source_user_name, " + "source_pass, column_name, sql_text, snapshot) " + "SELECT queue_id, 'failed' as status, queue_date, start_date, now() as end_date, " + "'Outsourcer stop requested' as error_message, num_rows, id, refresh_type, target_schema_name, " + "target_table_name, target_append_only, target_compressed, target_row_orientation, source_type, " + "source_server_name, source_instance_name, source_port, source_database_name, source_schema_name, " + "source_table_name, source_user_name, source_pass, column_name, sql_text, snapshot " + "FROM os.queue WHERE status = 'queued'"; 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() + ")"); } }
/** * This method queries the database to validate the passed in FRN for the selected Funding Year * * @exception SQLException, if query fails * @author */ public boolean validateFRN(String frn, String year) { String query; boolean validfrn = false; Statement stmt = null; ResultSet rs = null; query = "select wo_id from wrk_ordr where wrk_ordr_no='" + frn + "' and yr_fk=" + year; USFEnv.getLog().writeCrit("RhccDinvview: FRN query " + query, this, null); try { stmt = conn.createStatement(); rs = stmt.executeQuery(query); if (rs.next()) { validfrn = true; if (rs != null) rs.close(); if (stmt != null) stmt.close(); return true; } } catch (SQLException ex) { USFEnv.getLog().writeCrit("RhccDinvview: FRN not valid for the Year ", 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 false; }
/** * This method queries the database to get the Invoice Number associated with the passes Invid * * @exception SQLException, if query fails * @author */ public long getInvID(String inv_no) { String query; long invID = 0; Statement stmt = null; ResultSet rs = null; query = "select inv_id from inv where inv_no=" + inv_no; try { stmt = conn.createStatement(); rs = stmt.executeQuery(query); if (rs.next()) { invID = rs.getLong(1); } if (rs != null) rs.close(); if (stmt != null) stmt.close(); } catch (SQLException ex) { USFEnv.getLog().writeCrit("Dinvview: The Invoice 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 (invID); }
/** * This method queries the database to get the Invoice Number associated with the passes Invid * * @exception SQLException, if query fails * @author */ public String getInvno(String invid) { String query; String invno = ""; Statement stmt = null; ResultSet rs = null; query = "select inv_no from rhcc_inv where rhcc_inv_id=" + invid; try { stmt = conn.createStatement(); rs = stmt.executeQuery(query); if (rs.next()) { invno = rs.getString(1); } if (rs != null) rs.close(); if (stmt != null) stmt.close(); } catch (SQLException ex) { USFEnv.getLog().writeCrit("RhccDinvview: The Invoice Number 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 invno; }
/** * This method queries the database to get the SPIN associated with the passes Invid * * @exception SQLException, if query fails * @author */ public String getSPINname(String invid) { String query; String spinnm = ""; Statement stmt = null; ResultSet rs = null; // query = "select slc_nm from usw_co,inv where uc_id=uc_id_fk and inv_id="+invid; query = "select srv_provr_nm from srv_provr,rhcc_inv where spin = rhcc_inv.spin_fk and rhcc_inv_id=" + invid; try { stmt = conn.createStatement(); rs = stmt.executeQuery(query); if (rs.next()) { spinnm = rs.getString(1); } if (rs != null) rs.close(); if (stmt != null) stmt.close(); } catch (SQLException ex) { USFEnv.getLog().writeCrit("RhccDinvview: The SPIN Name 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 spinnm; }
// Get a list of images that have been added, but not yet added into // the database. protected void doFlush() { SpyDB pdb = getDB(); Vector v = null; try { Connection db = pdb.getConn(); Statement st = db.createStatement(); String query = "select * from upload_log where stored is null"; ResultSet rs = st.executeQuery(query); v = new Vector(); while (rs.next()) { v.addElement(rs.getString("photo_id")); } } catch (Exception e) { // Do nothing, we'll try again later. } finally { pdb.freeDBConn(); } // Got the vector, now store the actual images. This is done so // that we don't hold the database connection open whlie we're // making the list *and* getting another database connection to act // on it. if (v != null) { try { for (int i = 0; i < v.size(); i++) { String stmp = (String) v.elementAt(i); storeImage(Integer.valueOf(stmp).intValue()); } } catch (Exception e) { // Don't care, we'll try again soon. } } }
/** * 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(); }
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() + ")"); } }
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() + ")"); } }
// execute and get results private void execute(Connection conn, String text, Writer writer, boolean commaSeparator) throws SQLException { BufferedWriter buffer = new BufferedWriter(writer); Statement stmt = conn.createStatement(); stmt.execute(text); ResultSet rs = stmt.getResultSet(); ResultSetMetaData metadata = rs.getMetaData(); int nbCols = metadata.getColumnCount(); String[] labels = new String[nbCols]; int[] colwidths = new int[nbCols]; int[] colpos = new int[nbCols]; int linewidth = 1; // read each occurrence try { while (rs.next()) { for (int i = 0; i < nbCols; i++) { Object value = rs.getObject(i + 1); if (value != null) { buffer.write(value.toString()); if (commaSeparator) buffer.write(","); } } } buffer.flush(); rs.close(); } catch (IOException ex) { if (Debug.isDebug()) ex.printStackTrace(); // ok, exit from the loop } catch (SQLException ex) { if (Debug.isDebug()) ex.printStackTrace(); } }
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(); } }
/** * 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"); } }
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(); }
/** * 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; }
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); } }
public void carga_default() { Connection con = null; Statement st = null; try { Class.forName("com.mysql.jdbc.Driver").newInstance(); con = DriverManager.getConnection("jdbc:mysql://localhost/rsu_inventario", "root", pass); try { st = con.createStatement(); st.executeUpdate( "INSERT INTO ADMIN VALUES ('174183767','msX','msx','estudiante','santiago'," + "'2130','3030303','30303030','los valdios 3030','*****@*****.**',12345);"); } catch (SQLException s) { SQL_FORM error = new SQL_FORM(); JOptionPane.showMessageDialog(error, "error al ingresar datos"); // SQL_FORM error = new SQL_FORM(); JOptionPane.showMessageDialog(error, s, "alert", JOptionPane.ERROR_MESSAGE); } finally { con.close(); st.close(); } } catch (Exception e) { e.printStackTrace(); } }
public static void main(String args[]) { int myport = 9090; Socket s; ServerSocket ss; BufferedReader fromSoc, fromKbd; PrintStream toSoc; String line, msg; try { s = new Socket("169.254.63.10", 6016); System.out.println("enter line"); System.out.println("connected"); toSoc = new PrintStream(s.getOutputStream()); toSoc.println(myport); String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)}; DBQ=D://db.mdb; DriverID=22;READONLY=true;"; Connection con = DriverManager.getConnection(url, "", ""); Statement st = con.createStatement(); String ip = "169.254.63.10"; int port = 6016; String video = "rooney"; st.executeUpdate( " insert into p3 values('" + ip + "' , '" + port + "' , '" + video + "' ); "); fun(); } catch (Exception e) { System.out.println("exception" + e); } }
/* 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; }
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 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 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; }