public static void closeConnect() { try { con.close(); } catch (SQLException e) { MessageBox.infoBox(e.toString(), "Error in closeConnect"); } }
/** * Maps attributes of an SQL structured type that are not serialized to a serialized form, using * the given type map for custom mapping when appropriate. The following types in the Java * programming language are mapped to their serialized forms: <code>Struct</code>, <code>SQLData * </code>, <code>Ref</code>, <code>Blob</code>, <code>Clob</code>, and <code>Array</code>. * * <p>This method is called internally and is not used by an application programmer. * * @param map a <code>java.util.Map</code> object in which each entry consists of 1) a <code> * String</code> object giving the fully qualified name of a UDT and 2) the <code>Class</code> * object for the <code>SQLData</code> implementation that defines how the UDT is to be mapped * @throws SerialException if an error occurs */ private void mapToSerial(Map map) throws SerialException { try { for (int i = 0; i < attribs.length; i++) { if (attribs[i] instanceof Struct) { attribs[i] = new SerialStruct((Struct) attribs[i], map); } else if (attribs[i] instanceof SQLData) { attribs[i] = new SerialStruct((SQLData) attribs[i], map); } else if (attribs[i] instanceof Blob) { attribs[i] = new SerialBlob((Blob) attribs[i]); } else if (attribs[i] instanceof Clob) { attribs[i] = new SerialClob((Clob) attribs[i]); } else if (attribs[i] instanceof Ref) { attribs[i] = new SerialRef((Ref) attribs[i]); } else if (attribs[i] instanceof java.sql.Array) { attribs[i] = new SerialArray((java.sql.Array) attribs[i], map); } } } catch (SQLException e) { throw new SerialException(e.getMessage()); } return; }
/** Creates a Pooled connection and adds it to the connection pool. */ private void installConnection() throws EmanagerDatabaseException { logger.debug("enter"); PooledConnection connection; try { connection = poolDataSource.getPooledConnection(); connection.addConnectionEventListener(this); connection.getConnection().setAutoCommit(false); synchronized (connectionPool) { connectionPool.add(connection); logger.debug("Database connection added."); } } catch (SQLException ex) { logger.fatal("exception caught while obtaining database " + "connection: ex = " + ex); SQLException ex1 = ex.getNextException(); while (ex1 != null) { logger.fatal("chained sql exception ex1 = " + ex1); SQLException nextEx = ex1.getNextException(); ex1 = nextEx; } String logString; EmanagerDatabaseException ede; logString = EmanagerDatabaseStatusCode.DatabaseConnectionFailure.getStatusCodeDescription() + ex.getMessage(); logger.fatal(logString); ede = new EmanagerDatabaseException( EmanagerDatabaseStatusCode.DatabaseConnectionFailure, logString); throw ede; } }
private void submitButtonActionPerformed( java.awt.event.ActionEvent evt) { // GEN-FIRST:event_submitButtonActionPerformed // TODO add your handling code here: Connection con = FrameLogin.getConnect(); String SQLInsert = "INSERT INTO `2761DB`.`Persons` (`FirstName`, `LastName`, `CellPhoneNo`, `HomePhoneNo`, " + "`SchoolId`, `Graduation Year`, `Gender`) VALUES ('" + firstName.getText() + "', '" + lastName.getText() + "', '" + cellPhone.getText() + "', '" + homePhone.getText() + "', '" + studentId.getText() + "', '" + gradYear.getText() + "', '" + (String) (gender.getSelectedItem()) + "');"; String SQLUpdate = "UPDATE `2761DB`.`Persons` SET `FirstName` = '" + firstName.getText() + "', `LastName` = '" + lastName.getText() + "', `CellPhoneNo` = ' " + cellPhone.getText() + "', `HomePhoneNo` = '" + homePhone.getText() + "', `Graduation Year` = '" + gradYear.getText() + "', `Gender` = '" + (String) (gender.getSelectedItem()) + "' WHERE `PersonId` = '" + Id + "';"; // UPDATE `2761DB`.`Persons` SET `FirstName`='Robbie', `LastName`='Tacescu', `CellPhoneNo`='', // `HomePhoneNo`='559300', `SchoolId`='15648916', `Graduation Year`='6545', `Gender`='males' // WHERE // `PersonId`='42'; try { if (isEdit) { Statement stmt = con.createStatement(); // System.out.println(SQLUpdate); stmt.executeUpdate(SQLUpdate); } else { Statement stmt = con.createStatement(); // System.out.println(SQLInsert); stmt.executeUpdate(SQLInsert); } } catch (SQLException err) { MessageBox.infoBox(err.toString(), "Error in AddUserForm submitButton"); } FrameLogin.closeConnect(); this.dispose(); } // GEN-LAST:event_submitButtonActionPerformed
/** * Gets the ConnectionID attribute of the SybaseConnector class * * @param connection * @return The ConnectionID value */ public static long getConnectionID(Connection connection) { try { Statement stmt = connection.createStatement(); ResultSet res = stmt.executeQuery("select connection_property('Number')"); res.next(); return res.getLong(1); } catch (SQLException ex) { logger.error("SQL exception retrieving connection ID:" + ex.getMessage()); } return InvalidConnectionId; }
private void logIn(int personId) { Connection con = getConnect(); try { // MessageBox.infoBox("You have successfully logged in", "Login"); // INSERT INTO LogInOut (PersonId, TimeIn) VALUES (1, NOW()) String SQLLogin = "******" + personId + ", NOW())"; Statement stmtLogin = con.createStatement(); stmtLogin.executeUpdate(SQLLogin); Update_table(); } catch (SQLException err) { MessageBox.infoBox(err.toString(), "Error"); } closeConnect(); }
/** * Constructs a <code>SerialStruct</code> object from the given <code>SQLData</code> object, using * the given type map to custom map it to a class in the Java programming language. The type map * gives the SQL type and the class to which it is mapped. The <code>SQLData</code> object defines * the class to which the SQL type will be mapped. * * @param in an instance of the <code>SQLData</code> class that defines the mapping of the SQL * structured type to one or more objects in the Java programming language * @param map a <code>java.util.Map</code> object in which each entry consists of 1) a <code> * String</code> object giving the fully qualified name of a UDT and 2) the <code>Class</code> * object for the <code>SQLData</code> implementation that defines how the UDT is to be mapped * @throws SerialException if an error occurs */ public SerialStruct(SQLData in, Map<String, Class<?>> map) throws SerialException { try { // set the type name SQLTypeName = new String(in.getSQLTypeName()); Vector tmp = new Vector(); in.writeSQL(new SQLOutputImpl(tmp, map)); attribs = tmp.toArray(); } catch (SQLException e) { throw new SerialException(e.getMessage()); } }
public static Connection getConnect() { try { /*if (!getConnect) { if (!con.isValid(1)) {*/ String host = "jdbc:mysql://localhost:3306/2761DB"; String uname = "root"; String upassword = "******"; con = DriverManager.getConnection(host, uname, upassword); getConnect = true; /*} }*/ } catch (SQLException err) { System.out.println(err.getMessage()); } return con; }
private void logOut(int personId) { Connection con = getConnect(); try { // MessageBox.infoBox("You have successfully logged out", "Logout"); // UPDATE LogInOut SET TimeOut = NOW() WHERE PersonId = 1 AND TimeOut IS NULL String SQLLogin = "******" + personId + " AND TimeOut IS NULL"; Statement stmtLogin = con.createStatement(); stmtLogin.executeUpdate(SQLLogin); Update_table(); } catch (SQLException err) { System.out.println(err); MessageBox.infoBox(err.toString(), "Error"); } closeConnect(); }
public static void createConnectionPool() { Context context; try { context = new InitialContext(); Class.forName("org.firebirdsql.jdbc.FBDriver"); ds = (DataSource) context.lookup("java:comp/env/jdbc/PanelTrackDB"); Connection c = ds.getConnection(); } catch (NamingException e) { // TODO Auto-generated catch block errorLogger.error("An Error Occured:", e); e.printStackTrace(); } catch (ClassNotFoundException e) { errorLogger.error("An Error Occured:", e); // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { errorLogger.error("An Error Occured:", e); // TODO Auto-generated catch block e.printStackTrace(); } }
public static Connection obtenerConexion() throws NamingException { Connection conexion = null; try { // Creamos un contexto jndi inicial // Este context no tiene nada que ver con // la etiqueta contexto donde esta el pool // Este context hace referencia un servicio de nombres // naming service Context ctx = new InitialContext(); String nombreDelContextJNDI = "java:comp/env/"; DataSource ds = (DataSource) ctx.lookup(nombreDelContextJNDI + "jdbc/MySqlPoolConections"); conexion = ds.getConnection(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return conexion; }
public static boolean isIdFound(int id) { Connection con = getConnect(); boolean isFound = false; try { String SQL = "SELECT PersonId, FirstName, LastName, SchoolId FROM 2761DB.Persons WHERE SchoolId = " + id; Statement stmt = con.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); ResultSet rs = stmt.executeQuery(SQL); if (rs.first()) { isFound = true; } else { AddUserQuery addUser = new AddUserQuery(); addUser.setVisible(true); } } catch (SQLException err) { System.out.println(err); MessageBox.infoBox(err.toString(), "Error"); } closeConnect(); return isFound; }
/** * Constructs a <code>SerialStruct</code> object from the given <code>Struct</code> object, using * the given <code>java.util.Map</code> object for custom mapping the SQL structured type or any * of its attributes that are SQL structured types. * * @param map a <code>java.util.Map</code> object in which each entry consists of 1) a <code> * String</code> object giving the fully qualified name of a UDT and 2) the <code>Class</code> * object for the <code>SQLData</code> implementation that defines how the UDT is to be mapped * @throws SerialException if an error occurs * @see java.sql.Struct */ public SerialStruct(Struct in, Map<String, Class<?>> map) throws SerialException { try { // get the type name SQLTypeName = new String(in.getSQLTypeName()); System.out.println("SQLTypeName: " + SQLTypeName); // get the attributes of the struct attribs = in.getAttributes(map); /* * the array may contain further Structs * and/or classes that have been mapped, * other types that we have to serialize */ mapToSerial(map); } catch (SQLException e) { throw new SerialException(e.getMessage()); } }
public static List<Movie> getAllMovies() { String query = "SELECT * FROM movie"; List<Movie> movies = new LinkedList<>(); try (Connection connection = Config.getConnection(); // step 1 Statement statement = connection.createStatement(); // step 2 ResultSet result = statement.executeQuery(query); ) { // step 3 and 4 while (result.next()) { // step 5 Movie movie = new Movie(); // you should be validating the following, // this is just an example to get you started movie.setName(result.getString(1)); movie.setYear(result.getDate(2).getYear()); movie.setUrl(result.getString(3)); movies.add(movie); } } catch (SQLException e) { System.err.println(e.getMessage()); System.err.println(e.getStackTrace()); } return movies; }
protected boolean executeOnlyIf(Connection con, String q) throws SQLException { if (q == null) return true; Statement stmt = null; try { stmt = con.createStatement(); q = q.replace("$PREFIX", getPrefix()); LOG.debug(" Executing query " + q); ResultSet rs = stmt.executeQuery(q); rs.next(); boolean res = rs.getBoolean(1); LOG.debug("Result: " + res); return res; } catch (SQLException sqe) { LOG.error(sqe.getMessage() + " from " + q); throw sqe; } finally { try { if (stmt != null) { stmt.close(); } } catch (Exception g) { } } }
public static void main(String[] args) { Connection con = null; Statement stat = null; String s; try { Class.forName("oracle.jdbc.driver.OracleDriver"); // con=DriverManager.getConnection("jdbc:oracle:oci8:@oracle9i","scott","tiger"); // // con=DriverManager.getConnection("jdbc:oracle:thin:@saraswati:1521:oracle10g","scott","tiger"); con = DriverManager.getConnection("jdbc:oracle:thin:@//localhost:1521/XE", "scott", "tiger"); /*Properties p=new Properties(); p.put("user","scott"); p.put("password","tiger");*/ // Driver d=(Driver)Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance(); // Connection con=d.connect("jdbc:odbc:oradsn",p); // Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); // con=DriverManager.getConnection("jdbc:odbc:namadsn","scott","tiger"); System.out.println("The connection is successful."); } catch (Exception e) { e.printStackTrace(); } try { stat = con.createStatement(); s = "create table student(Rollno int,Name varchar2(50),serName varchar2(50))"; stat.executeUpdate(s); } catch (SQLException e) { e.printStackTrace(); } try { stat = con.createStatement(); s = "insert into student values(1,'Namrata','Marathe')"; stat.executeUpdate(s); s = "insert into student values(2,'Arjun','Marathe')"; stat.executeUpdate(s); s = "insert into student values(3,'Rahul','Marathe')"; stat.executeUpdate(s); } catch (SQLException e) { e.printStackTrace(); } try { stat.close(); } catch (SQLException e) { } System.out.println("create is successful:"); try { stat = con.createStatement(); s = "select * from student"; ResultSet rset = stat.executeQuery(s); while (rset.next()) System.out.println(rset.getInt(1) + " " + rset.getString(2) + " " + rset.getString(3)); } catch (SQLException e) { e.printStackTrace(); } try { stat.close(); } catch (SQLException se) { } }
public synchronized Object invoke(Object proxy, Method m, Object[] args) throws Throwable { if (OBJECT_METHODS.contains(m)) return m.invoke(this, args); try { String mname = m.getName(); if (activeConnection != null) { if (mname.equals("rawConnectionOperation")) { ensureOkay(); txn_known_resolved = false; return doRawConnectionOperation((Method) args[0], args[1], (Object[]) args[2]); } else if (mname.equals("setTransactionIsolation")) { ensureOkay(); // don't modify txn_known_resolved m.invoke(activeConnection, args); int lvl = ((Integer) args[0]).intValue(); isolation_lvl_nondefault = (lvl != dflt_txn_isolation); // System.err.println("updated txn isolation to " + lvl + ", nondefault level? " + // isolation_lvl_nondefault); return null; } else if (mname.equals("setCatalog")) { ensureOkay(); // don't modify txn_known_resolved m.invoke(activeConnection, args); String catalog = (String) args[0]; catalog_nondefault = ObjectUtils.eqOrBothNull(catalog, dflt_catalog); return null; } else if (mname.equals("setHoldability")) { ensureOkay(); // don't modify txn_known_resolved m.invoke( activeConnection, args); // will throw an exception if setHoldability() not supported... int holdability = ((Integer) args[0]).intValue(); holdability_nondefault = (holdability != dflt_holdability); return null; } else if (mname.equals("createStatement")) { ensureOkay(); txn_known_resolved = false; Object stmt = m.invoke(activeConnection, args); return createProxyStatement((Statement) stmt); } else if (mname.equals("prepareStatement")) { ensureOkay(); txn_known_resolved = false; Object pstmt; if (scache == null) { pstmt = m.invoke(activeConnection, args); return createProxyStatement((Statement) pstmt); } else { pstmt = scache.checkoutStatement(physicalConnection, m, args); return createProxyStatement(true, (Statement) pstmt); } } else if (mname.equals("prepareCall")) { ensureOkay(); txn_known_resolved = false; Object cstmt; if (scache == null) { cstmt = m.invoke(activeConnection, args); return createProxyStatement((Statement) cstmt); } else { cstmt = scache.checkoutStatement(physicalConnection, m, args); return createProxyStatement(true, (Statement) cstmt); } } else if (mname.equals("getMetaData")) { ensureOkay(); txn_known_resolved = false; // views of tables etc. might be txn dependent DatabaseMetaData innerMd = activeConnection.getMetaData(); if (metaData == null) { // exposedProxy is protected by C3P0PooledConnection.this' lock synchronized (C3P0PooledConnection.this) { metaData = new SetManagedDatabaseMetaData(innerMd, activeMetaDataResultSets, exposedProxy); } } return metaData; } else if (mname.equals("silentClose")) { // the PooledConnection doesn't have to be okay doSilentClose(proxy, ((Boolean) args[0]).booleanValue(), this.txn_known_resolved); return null; } else if (mname.equals("close")) { // the PooledConnection doesn't have to be okay Exception e = doSilentClose(proxy, false, this.txn_known_resolved); if (!connection_error_signaled) ces.fireConnectionClosed(); // System.err.println("close() called on a ProxyConnection."); if (e != null) { // System.err.print("user close exception -- "); // e.printStackTrace(); throw e; } else return null; } // else if ( mname.equals("finalize") ) //REMOVE THIS CASE -- TMP DEBUG // { // System.err.println("Connection apparently finalized!"); // return m.invoke( activeConnection, args ); // } else { ensureOkay(); // we've disabled setting txn_known_resolved to true, ever, because // we failed to deal with the case that clients would work with previously // acquired Statements and ResultSets after a commit(), rollback(), or setAutoCommit(). // the new non-reflective proxies have been modified to deal with this case. // here, with soon-to-be-deprecated in "traditional reflective proxies mode" // we are reverting to the conservative, always-presume-you-have-to-rollback // policy. // txn_known_resolved = ( mname.equals("commit") || mname.equals( "rollback" ) || // mname.equals( "setAutoCommit" ) ); txn_known_resolved = false; return m.invoke(activeConnection, args); } } else { if (mname.equals("close") || mname.equals("silentClose")) return null; else if (mname.equals("isClosed")) return Boolean.TRUE; else { throw new SQLException("You can't operate on " + "a closed connection!!!"); } } } catch (InvocationTargetException e) { Throwable convertMe = e.getTargetException(); SQLException sqle = handleMaybeFatalToPooledConnection(convertMe, proxy, false); sqle.fillInStackTrace(); throw sqle; } }
/** * This method searches the table STAGE_USAC_FORM for the distinctfilename provided for the usac * refrence number given * * @param Stringusac refrence number * @return Vector containing the Result Set */ public Vector selectFileName(String rfrnc_nmbr) { // the buffer for the query StringBuffer sbQuery = null; Vector rsVector = new Vector(); PreparedStatement psStmt = null; ResultSet rsResult = null; try { // init the buffer sbQuery = new StringBuffer(""); // build the query sbQuery.append(buildSelectFileName()); sbQuery.append(" WHERE "); sbQuery.append(" rfrnc_nmbr = ?"); // sbQuery.append( rfrnc_nmbr ); // sbQuery.append("'"); USFEnv.getLog() .writeDebug( "Get FileName by USAC Ref Number is: " + sbQuery.toString() + "\n", this, null); // execute the query psStmt = cConn.prepareStatement(sbQuery.toString()); psStmt.setString(1, rfrnc_nmbr); rsResult = psStmt.executeQuery(); if (rsResult != null) { while (rsResult.next()) { rsVector.addElement(rsResult.getString("FILENAME")); USFEnv.getLog() .writeDebug(" THE FILENAME IS : " + rsResult.getString("FILENAME"), this, null); } } if (rsResult != null) rsResult.close(); if (psStmt != null) psStmt.close(); } catch (SQLException e) { try { // close the statment and the ResultSet if (rsResult != null) rsResult.close(); if (psStmt != null) psStmt.close(); } catch (SQLException ex) { USFEnv.getLog() .writeCrit("selectSQLCall(): Fail to close result set or prepare statement", this, ex); } USFEnv.getLog() .writeCrit( " SQL Exception : SQL Error message " + e.getMessage() + " with Query: \n" + sbQuery.toString(), this, e); } catch (Exception e) { try { // close the statment and the ResultSet if (rsResult != null) rsResult.close(); if (psStmt != null) psStmt.close(); } catch (SQLException ex) { USFEnv.getLog() .writeCrit("selectSQLCall(): Fail to close result set or prepare statement", this, ex); } USFEnv.getLog() .writeCrit( "Error Executing the Query(): Error executing query " + e.getMessage(), this, e); } /* try { // close the statment and the ResultSet if (rsResult != null) rsResult.close(); if (psStmt != null) psStmt.close(); } catch (SQLException e) { USFEnv.getLog().writeCrit("selectSQLCall(): Fail to close result set or prepare statement",this, e); }*/ return rsVector; }
/** * @return Connection * @roseuid 3F3A5FFD0338 */ public Connection getConnection() throws EmanagerDatabaseException { long connectionId; Connection connection; PooledConnection pooledConnection; connection = null; pooledConnection = null; connectionId = InvalidConnectionId; try { synchronized (connectionPool) { if (!connectionPool.isEmpty()) { try { boolean connectionClosed; connectionClosed = false; pooledConnection = (PooledConnection) connectionPool.remove(0); connection = pooledConnection.getConnection(); connection.clearWarnings(); connectionId = getConnectionID(connection); connectionClosed = connection.isClosed(); if (connectionId == InvalidConnectionId || connectionClosed == true) { logger.debug("Pooled connection closed."); connection = null; } } catch (SQLException sqe) { logger.debug("Pooled connection closed."); connection = null; } } } if (connection == null) { logger.debug("Getting a new connection."); pooledConnection = poolDataSource.getPooledConnection(); pooledConnection.addConnectionEventListener(this); connection = pooledConnection.getConnection(); connection.clearWarnings(); connectionId = getConnectionID(connection); } } catch (SQLException sqe) { String logString; EmanagerDatabaseException ede; logString = EmanagerDatabaseStatusCode.UnableToGetPooledConnection.getStatusCodeDescription() + sqe.getMessage(); logger.error(logString); ede = new EmanagerDatabaseException( EmanagerDatabaseStatusCode.UnableToGetPooledConnection, logString); throw ede; } if (connectionId == InvalidConnectionId) { EmanagerDatabaseException ede; ede = new EmanagerDatabaseException( EmanagerDatabaseStatusCode.UnableToGetPooledConnection, EmanagerDatabaseStatusCode.UnableToGetPooledConnection.getStatusCodeDescription()); throw ede; } logger.debug( "\n*****************************" + "\nPooled Connection Init" + "\nCon ID:" + connectionId + "\nCon Object:" + pooledConnection + "\nPool Object:" + connection + "\n*****************************"); return connection; }