Java Code Examples for java.sql.Statement
The following code examples are extracted from open source projects. You can click to
vote up the examples that are useful to you.
Example 1
From project b3log-latke, under directory /latke/src/main/java/org/b3log/latke/repository/jdbc/util/.
Source file: JdbcUtil.java

/** * executeSql. * @param sql sql * @param connection connection * @return ifsuccess * @throws SQLException SQLException */ public static boolean executeSql(final String sql,final Connection connection) throws SQLException { LOGGER.log(Level.FINEST,"executeSql: {0}",sql); final Statement statement=connection.createStatement(); final boolean isSuccess=!statement.execute(sql); statement.close(); return isSuccess; }
Example 2
From project activejdbc, under directory /activejdbc/src/test/java/org/javalite/activejdbc/test/.
Source file: DefaultDBReset.java

static void resetSchema(String[] statements) throws SQLException { Connection connection=Base.connection(); for ( String statement : statements) { if (Util.blank(statement)) continue; Statement st=connection.createStatement(); st.executeUpdate(statement); st.close(); } }
Example 3
From project agileBase, under directory /gtpb_server/src/com/gtwm/pb/model/manageData/.
Source file: ReportData.java

/** * Calling methods should always revert back to enable=true at the end of querying * @param enableNestLoop true = enable nested loops in queries (default), false = disable */ public static void enableNestloop(Connection conn,boolean enableNestLoop) throws SQLException { Statement setNestedLoopStatement=conn.createStatement(); if (enableNestLoop) { setNestedLoopStatement.execute("SET enable_nestloop=true"); } else { setNestedLoopStatement.execute("SET enable_nestloop=false"); } setNestedLoopStatement.close(); }
Example 4
From project airlift, under directory /dbpool/src/main/java/io/airlift/dbpool/.
Source file: H2EmbeddedDataSource.java

private static void setConfig(Connection connection,String name,Object value) throws SQLException { Statement statement=connection.createStatement(); try { String command=String.format("SET %s %s",name,value); int count=statement.executeUpdate(command); if (count != 0) { throw new SQLException("Failed to execute command: " + command); } } finally { closeQuietly(statement); } }
Example 5
From project arastreju, under directory /arastreju.rdb/src/main/java/org/arastreju/bindings/rdb/jdbc/.
Source file: DBOperations.java

public static void deleteTable(Connection con,String tablename){ try { Statement smt=con.createStatement(); smt.execute("DROP TABLE " + tablename + ";"); } catch ( SQLException e) { e.printStackTrace(); } }
Example 6
From project autopsy, under directory /Core/src/org/sleuthkit/autopsy/datamodel/.
Source file: RecentFilesChildren.java

private long runTimeQuery(String query){ long result=0; try { ResultSet rs=skCase.runQuery(query); result=rs.getLong(1); Statement s=rs.getStatement(); rs.close(); if (s != null) s.close(); } catch ( SQLException ex) { Logger.getLogger(RecentFilesFilterChildren.class.getName()).log(Level.WARNING,"Couldn't get search results",ex); } return result; }
Example 7
From project bonecp, under directory /bonecp/src/main/java/com/jolbox/bonecp/.
Source file: ConnectionHandle.java

/** * Sends any configured SQL init statement. * @throws SQLException on error */ public void sendInitSQL() throws SQLException { String initSQL=this.pool.getConfig().getInitSQL(); if (initSQL != null) { Statement stmt=this.connection.createStatement(); stmt.execute(initSQL); stmt.close(); } }
Example 8
public Boolean tableExists(String table){ Boolean exists=false; try { Statement stat=conn.createStatement(); ResultSet rs=stat.executeQuery("SELECT name FROM sqlite_master WHERE name='" + table + "';"); exists=rs.next(); stat.close(); } catch ( Exception e) { System.err.println("[Catacombs] Sqlite error: " + e.getMessage()); } return exists; }
Example 9
From project caustic, under directory /console/src/net/caustic/database/.
Source file: JDBCSqliteConnection.java

@Override public void executeNow(String sql) throws SQLConnectionException { try { commit(); Statement stmt=connection.createStatement(); stmt.execute(sql); connection.commit(); stmt.close(); } catch ( SQLException e) { throw new SQLConnectionException(e); } }
Example 10
From project channel-directory, under directory /src/com/buddycloud/channeldirectory/crawler/.
Source file: PubSubServerCrawler.java

/** * @return * @throws SQLException */ private List<String> retrieveServers() throws SQLException { Statement statement=dataSource.createStatement(); ResultSet resultSet=statement.executeQuery("SELECT * FROM subscribed_server"); List<String> serversToCrawl=new LinkedList<String>(); while (resultSet.next()) { serversToCrawl.add(resultSet.getString("name")); } ChannelDirectoryDataSource.close(statement); return serversToCrawl; }
Example 11
From project ChessCraft, under directory /src/main/java/me/desht/chesscraft/results/.
Source file: Results.java

private void loadEntries(){ try { entries.clear(); Statement stmt=getConnection().createStatement(); ResultSet rs=stmt.executeQuery("SELECT * FROM results"); while (rs.next()) { ResultEntry e=new ResultEntry(rs); entries.add(e); } } catch ( SQLException e) { LogUtils.warning("SQL query failed: " + e.getMessage()); } }
Example 12
From project CIShell, under directory /core/org.cishell.reference.service.database/src/org/cishell/reference/service/database/utility/.
Source file: DatabaseCleaner.java

private static void removeRoles(Connection conn) throws SQLException { Statement stm=conn.createStatement(); Statement dropStm=conn.createStatement(); ResultSet rs=stm.executeQuery("select roleid from sys.sysroles where " + "cast(isdef as char(1)) = 'Y'"); while (rs.next()) { dropStm.executeUpdate("DROP ROLE " + JDBC.escape(rs.getString(1))); } stm.close(); dropStm.close(); conn.commit(); }
Example 13
From project codjo-broadcast, under directory /codjo-broadcast-common/src/main/java/net/codjo/broadcast/common/computed/.
Source file: GeneratedDateField.java

/** * Remplissage de la colonne avec la date et l'heure de generation * @param ctxt context de la colonne calculee (contient les noms des tablesutilisees...) * @param con * @exception SQLException */ public void compute(ComputedContext ctxt,Connection con) throws SQLException { Statement stmt=con.createStatement(); try { stmt.executeUpdate("update " + ctxt.getComputedTableName() + " set "+ getName()+ " = getDate()"); } finally { stmt.close(); } }
Example 14
From project codjo-control, under directory /codjo-control-common/src/main/java/net/codjo/control/common/.
Source file: IntegrationPlan.java

private void deleteControlTable(Connection con) throws SQLException { Statement stmt=con.createStatement(); try { stmt.executeUpdate("delete from " + getControlTableName()); } catch ( SQLException e) { APP.debug("Delete de la table " + getControlTableName(),e); } finally { stmt.close(); } }
Example 15
From project codjo-data-process, under directory /codjo-data-process-server/src/main/java/net/codjo/dataprocess/server/dao/.
Source file: UtilDao.java

public boolean executeSql(Connection con,String query) throws SQLException { Statement stmt=con.createStatement(); try { return stmt.execute(query); } finally { stmt.close(); } }
Example 16
From project codjo-imports, under directory /codjo-imports-common/src/main/java/net/codjo/imports/common/.
Source file: DeleteLinesProcessor.java

@Override public void preProceed(Connection con,String quarantineTableName,File file) throws SQLException { Statement stmt=con.createStatement(); try { stmt.executeUpdate("delete from " + quarantineTableName + ((whereClause != null) ? " where " + whereClause : "")); } finally { stmt.close(); } }
Example 17
From project codjo-segmentation, under directory /codjo-segmentation-server/src/main/java/net/codjo/segmentation/server/paramImport/.
Source file: AbstractDispatchManager.java

private void initColumnTypes() throws SQLException { columnTypes=new HashMap<String,String>(); String request="select col.name as columnName, fieldType.name as columnType " + "from syscolumns col " + "inner join systypes fieldType "+ "on col.usertype = fieldType.usertype "+ "where id=object_id('" + getDestinationTable() + "')"; Statement statement=connection.createStatement(); ResultSet resultSet=statement.executeQuery(request); while (resultSet.next()) { columnTypes.put(resultSet.getString("columnName"),resultSet.getString("columnType")); } closeStatement(statement); }
Example 18
From project codjo-shipment, under directory /src/main/java/net/codjo/shipment/.
Source file: DataShipmentHome.java

/** * Construit une HashMap ayant pour <code>code</code> la liste des <code>sourceSystem</code> trouve dans la table <code>PM_SOURCE_SYSTEM</code> et <code>valeur</code> un liste de {@link Translator} cree par rapport au type SQL<code>destTypeSQLField</code> . * @param con * @param destTypeSQLField Le type SQL du champ destination * @return La liste des {@link Translator} par <code>sourceSystem</code> * @exception SQLException - */ private static Map getAllSourceTranslator(Connection con,int destTypeSQLField) throws SQLException { HashMap sourceTranslator=new HashMap(); Statement stmt=con.createStatement(); try { ResultSet rs=stmt.executeQuery("select * from PM_SOURCE_SYSTEM"); while (rs.next()) { sourceTranslator.put(rs.getString("SOURCE_SYSTEM"),getNewTranslator(destTypeSQLField,rs.getString("DECIMAL_SEPARATOR"),rs.getString("DATE_FORMAT"))); } } finally { stmt.close(); } return sourceTranslator; }
Example 19
From project codjo-standalone-common, under directory /src/main/java/net/codjo/gui/broadcast/.
Source file: BroadcastColumnsDetailWindow.java

private String getFamily(String sectionId) throws SQLException { Connection con=CONNECTION_MANAGER.getConnection(); Statement stmt=con.createStatement(); try { ResultSet rs=stmt.executeQuery("select FAMILY " + " from " + GUI_PREFERENCES_MANAGER.getSectionTableName() + " where SECTION_ID = "+ sectionId); if (!rs.next()) { throw new IllegalArgumentException("Section inconnue id " + sectionId); } return rs.getString(1); } finally { CONNECTION_MANAGER.releaseConnection(con,stmt); } }
Example 20
From project adbcj, under directory /jdbc/src/main/java/org/adbcj/jdbc/.
Source file: JdbcConnection.java

public DbSessionFuture<Result> executeUpdate(final String sql){ checkClosed(); return enqueueTransactionalRequest(new CallableRequest<Result>(){ public Result doCall() throws Exception { Statement statement=jdbcConnection.createStatement(); try { statement.execute(sql); List<String> warnings=new LinkedList<String>(); SQLWarning sqlWarnings=statement.getWarnings(); while (sqlWarnings != null) { warnings.add(sqlWarnings.getLocalizedMessage()); sqlWarnings=sqlWarnings.getNextWarning(); } return new DefaultResult((long)statement.getUpdateCount(),warnings); } finally { statement.close(); } } } ); }
Example 21
From project AdminCmd, under directory /src/main/java/lib/SQL/PatPeter/SQLibrary/.
Source file: Database.java

/** * <b>createTable</b><br> <br> Creates a table in the database based on a specified query. <br> <br> * @param query - the SQL query for creating a table. * @return the success of the method. */ public boolean createTable(final String query){ Statement statement=null; try { if (query.equals("") || query == null) { this.writeError("Parameter 'query' empty or null in createTable().",true); return false; } synchronized (connection) { statement=connection.createStatement(); statement.execute(query); } return true; } catch ( final SQLException ex) { this.writeError(ex.getMessage(),true); return false; } }
Example 22
From project AdServing, under directory /modules/services/geo/src/main/java/net/mad/ads/services/geo/.
Source file: IpinfoLocationDB.java

public Location searchIp(String ip){ Connection conn=null; Statement stat=null; try { conn=poolMgr.getConnection(); stat=conn.createStatement(); long inetAton=ValidateIP.ip2long(ip); String query="SELECT * FROM IP_COUNTRY WHERE ipFROM <= " + inetAton + " ORDER BY ipFROM DESC LIMIT 1"; ResultSet result=stat.executeQuery(query); while (result.next()) { String c=result.getString("countrySHORT"); String rn=result.getString("ipREGION"); String cn=result.getString("ipCITY"); String lat=result.getString("ipLATITUDE"); String lng=result.getString("ipLONGITUDE"); Location loc=new Location(c,rn,cn,lat,lng); return loc; } return Location.UNKNOWN; } catch ( Exception e) { e.printStackTrace(); } finally { try { conn.close(); stat.close(); } catch ( Exception e) { e.printStackTrace(); } } return null; }
Example 23
From project akubra, under directory /akubra-txn/src/main/java/org/akubraproject/txn/derby/.
Source file: TransactionalStore.java

private void createTables() throws IOException { runInCon(new Action<Void>(){ public Void run( Connection con) throws SQLException { ResultSet rs=con.getMetaData().getTables(null,null,NAME_TABLE,null); try { if (rs.next()) return null; } finally { rs.close(); } logger.info("Creating tables and indexes for name-map"); Statement stmt=con.createStatement(); try { stmt.execute("CREATE TABLE " + NAME_TABLE + " (appId VARCHAR(1000) NOT NULL, storeId VARCHAR(1000) NOT NULL, "+ " version BIGINT NOT NULL, deleted SMALLINT, committed SMALLINT)"); stmt.execute("CREATE INDEX " + NAME_TABLE + "_AIIDX ON "+ NAME_TABLE+ "(appId)"); stmt.execute("CREATE INDEX " + NAME_TABLE + "_VIDX ON "+ NAME_TABLE+ "(version)"); stmt.execute("CREATE TABLE " + DEL_TABLE + " (appId VARCHAR(1000) NOT NULL, "+ " storeId VARCHAR(1000), version BIGINT NOT NULL)"); stmt.execute("CREATE INDEX " + DEL_TABLE + "_VIDX ON "+ DEL_TABLE+ "(version)"); stmt.execute("CALL SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY('derby.locks.escalationThreshold', '" + Integer.MAX_VALUE + "')"); stmt.execute("CALL SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY('derby.locks.deadlockTimeout', '30')"); } finally { stmt.close(); } return null; } } ,"Failed to create tables"); }
Example 24
From project ardverk-dht, under directory /components/store/src/main/java/org/ardverk/dht/storage/sql/.
Source file: DefaultIndex.java

public static DefaultIndex create(File dir,int length){ try { ConnectionManager cm=ConnectionManager.newInstance(dir); StatementFactory factory=new StatementFactory(length); Statement statement=cm.createStatement(); statement.addBatch(factory.createBuckets()); statement.addBatch(factory.createKeys()); statement.addBatch(factory.createValues()); statement.addBatch(factory.createProperties()); statement.executeBatch(); statement.close(); return new DefaultIndex(factory,cm); } catch ( ClassNotFoundException e) { throw new IllegalStateException("ClassNotFoundException",e); } catch ( SQLException e) { throw new IllegalStateException("SQLException",e); } }
Example 25
From project arquillian-extension-persistence, under directory /impl/src/main/java/org/jboss/arquillian/persistence/core/data/script/.
Source file: ScriptExecutor.java

private void executeSingleStatement(String line){ Statement statement=null; try { statement=connection.createStatement(); statement.execute(line); } catch ( Exception e) { throw new DBUnitDataSetHandlingException("Unable to execute line: " + line,e); } finally { if (statement != null) { try { statement.close(); } catch ( SQLException e) { throw new DBUnitDataSetHandlingException("Unable to close statement after script execution.",e); } } } }
Example 26
From project authme-2.0, under directory /src/uk/org/whoami/authme/datasource/.
Source file: MySQLDataSource.java

private synchronized void setup() throws SQLException { Connection con=null; Statement st=null; ResultSet rs=null; try { con=conPool.getValidConnection(); st=con.createStatement(); st.executeUpdate("CREATE TABLE IF NOT EXISTS " + tableName + " ("+ "id INTEGER AUTO_INCREMENT,"+ columnName+ " VARCHAR(255) NOT NULL,"+ columnPassword+ " VARCHAR(255) NOT NULL,"+ columnIp+ " VARCHAR(40) NOT NULL,"+ columnLastLogin+ " BIGINT,"+ "CONSTRAINT table_const_prim PRIMARY KEY (id));"); rs=con.getMetaData().getColumns(null,null,tableName,columnIp); if (!rs.next()) { st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN "+ columnIp+ " VARCHAR(40) NOT NULL;"); } rs.close(); rs=con.getMetaData().getColumns(null,null,tableName,columnLastLogin); if (!rs.next()) { st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN "+ columnLastLogin+ " BIGINT;"); } } finally { close(rs); close(st); close(con); } ConsoleLogger.info("MySQL Setup finished"); }
Example 27
From project AuthMe-Reloaded, under directory /src/main/java/uk/org/whoami/authme/datasource/.
Source file: MySQLDataSource.java

private synchronized void setup() throws SQLException { Connection con=null; Statement st=null; ResultSet rs=null; try { con=conPool.getValidConnection(); st=con.createStatement(); st.executeUpdate("CREATE TABLE IF NOT EXISTS " + tableName + " ("+ "id INTEGER AUTO_INCREMENT,"+ columnName+ " VARCHAR(255) NOT NULL UNIQUE,"+ columnPassword+ " VARCHAR(255) NOT NULL,"+ columnIp+ " VARCHAR(40) NOT NULL,"+ columnLastLogin+ " BIGINT,"+ "x smallint(6) DEFAULT '0',"+ "y smallint(6) DEFAULT '0',"+ "z smallint(6) DEFAULT '0',"+ "CONSTRAINT table_const_prim PRIMARY KEY (id));"); rs=con.getMetaData().getColumns(null,null,tableName,columnIp); if (!rs.next()) { st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN "+ columnIp+ " VARCHAR(40) NOT NULL;"); } rs.close(); rs=con.getMetaData().getColumns(null,null,tableName,columnLastLogin); if (!rs.next()) { st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN "+ columnLastLogin+ " BIGINT;"); } rs.close(); rs=con.getMetaData().getColumns(null,null,tableName,"x"); if (!rs.next()) { st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN x smallint(6) NOT NULL DEFAULT '0' AFTER "+ columnLastLogin+ " , ADD y smallint(6) NOT NULL DEFAULT '0' AFTER x , ADD z smallint(6) NOT NULL DEFAULT '0' AFTER y;"); } } finally { close(rs); close(st); close(con); } ConsoleLogger.info("MySQL Setup finished"); }
Example 28
From project AuthMe-Reloaded-Charge-fix, under directory /src/uk/org/whoami/authme/datasource/.
Source file: MySQLDataSource.java

private synchronized void setup() throws SQLException { Connection con=null; Statement st=null; ResultSet rs=null; try { con=conPool.getValidConnection(); st=con.createStatement(); st.executeUpdate("CREATE TABLE IF NOT EXISTS " + tableName + " ("+ "id INTEGER AUTO_INCREMENT,"+ columnName+ " VARCHAR(255) NOT NULL UNIQUE,"+ columnPassword+ " VARCHAR(255) NOT NULL,"+ columnIp+ " VARCHAR(40) NOT NULL,"+ columnLastLogin+ " BIGINT,"+ "x smallint(6) DEFAULT '0',"+ "y smallint(6) DEFAULT '0',"+ "z smallint(6) DEFAULT '0',"+ "CONSTRAINT table_const_prim PRIMARY KEY (id));"); rs=con.getMetaData().getColumns(null,null,tableName,columnIp); if (!rs.next()) { st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN "+ columnIp+ " VARCHAR(40) NOT NULL;"); } rs.close(); rs=con.getMetaData().getColumns(null,null,tableName,columnLastLogin); if (!rs.next()) { st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN "+ columnLastLogin+ " BIGINT;"); } rs.close(); rs=con.getMetaData().getColumns(null,null,tableName,"x"); if (!rs.next()) { st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN x smallint(6) NOT NULL DEFAULT '0' AFTER "+ columnLastLogin+ " , ADD y smallint(6) NOT NULL DEFAULT '0' AFTER x , ADD z smallint(6) NOT NULL DEFAULT '0' AFTER y;"); } } finally { close(rs); close(st); close(con); } ConsoleLogger.info("MySQL Setup finished"); }
Example 29
From project autopatch, under directory /src/test/java/com/tacitknowledge/util/migration/jdbc/.
Source file: SqlScriptMigrationTaskTest.java

/** * Test that sybase database patches are committed when illegal multi statement transaction commands are used. * @throws IOException if an unexpected error occurs * @throws MigrationException if an unexpected error occurs * @throws SQLException if an unexpected error occurs */ public void testSybasePatchesCommitsOnEveryStatement() throws IOException, MigrationException, SQLException { InputStream is=getClass().getResourceAsStream("test/sybase_tsql.sql"); assertNotNull(is); task=new SqlScriptMigrationTask("sybase_tsql.sql",1,is); MockDatabaseType dbType=new MockDatabaseType("sybase"); dbType.setMultipleStatementsSupported(false); context.setDatabaseType(dbType); int numStatements=task.getSqlStatements(context).size(); MockControl dataSourceControl=MockControl.createControl(DataSource.class); DataSource dataSource=(DataSource)dataSourceControl.getMock(); context.setDataSource(dataSource); MockControl connectionControl=MockControl.createControl(Connection.class); Connection connection=(Connection)connectionControl.getMock(); dataSourceControl.expectAndReturn(dataSource.getConnection(),connection); MockControl statementControl=MockControl.createControl(Statement.class); Statement statement=(Statement)statementControl.getMock(); statement.execute(""); statementControl.setMatcher(MockControl.ALWAYS_MATCHER); statementControl.setReturnValue(true,MockControl.ONE_OR_MORE); statementControl.expectAndReturn(statement.isClosed(),false,MockControl.ONE_OR_MORE); statement.close(); statementControl.setVoidCallable(MockControl.ONE_OR_MORE); connectionControl.expectAndReturn(connection.isClosed(),false,MockControl.ONE_OR_MORE); connectionControl.expectAndReturn(connection.createStatement(),statement,numStatements); connectionControl.expectAndReturn(connection.getAutoCommit(),false,MockControl.ONE_OR_MORE); connection.commit(); connectionControl.setVoidCallable(4); dataSourceControl.replay(); connectionControl.replay(); statementControl.replay(); task.migrate(context); dataSourceControl.verify(); connectionControl.verify(); }
Example 30
From project azure4j-blog-samples, under directory /Caching/MemcachedWebApp/src/com/persistent/dao/.
Source file: EmployeeDao.java

/** * Returns the list of all employees. * @return the list of employees. * @throws SQLException */ public List<Employee> getAllEmployees() throws SQLException { Connection connection=null; Statement statement=null; List<Employee> employees=new ArrayList<Employee>(); try { connection=DBConnectionUtil.getConnection(); statement=connection.createStatement(); ResultSet resultSet=statement.executeQuery("select * from Employees"); Employee employee=null; while (resultSet.next()) { employee=new Employee(); employee.setEmpId(resultSet.getInt("empId")); employee.setFirstName(resultSet.getString("firstName")); employee.setLastName(resultSet.getString("lastName")); employee.setDepartment(resultSet.getString("department")); employees.add(employee); } } finally { try { if (statement != null) { statement.close(); } if (connection != null) { connection.close(); } } catch ( SQLException e) { e.printStackTrace(); } } return employees; }
Example 31
From project brix-cms, under directory /brix-rmiserver/src/main/java/org/brixcms/rmiserver/boot/.
Source file: Bootstrapper.java

/** * @param sf */ private void bootstrapSchema(){ Connection con=null; try { con=datasource.getConnection(); Dialect dialect=Dialect.getDialect(configuration.getProperties()); String[] schema=configuration.generateSchemaCreationScript(dialect); for ( String stmt : schema) { Statement st=con.createStatement(); st.executeUpdate(stmt); st.close(); } con.commit(); } catch ( SQLException e1) { if (con != null) { try { con.rollback(); } catch ( SQLException e2) { try { con.close(); } catch ( SQLException e3) { } } } } }
Example 32
From project Carolina-Digital-Repository, under directory /djatoka-cdr/src/gov/lanl/adore/djatoka/openurl/plugin/rftdb/.
Source file: DatabaseResolver.java

private ImageRecord getLocalImage(String rftId){ ImageRecord ir=localImgs.get(rftId); if (ir == null) { Connection conn=null; Statement stmt=null; ResultSet rset=null; try { conn=dataSource.getConnection(); stmt=conn.createStatement(); rset=stmt.executeQuery(query.replace("\\i",rftId)); if (rset.next()) { ir=new ImageRecord(); ir.setIdentifier(rset.getString(FIELD_IDENTIFIER)); ir.setImageFile(rset.getString(FIELD_IMAGEFILE)); } } catch ( SQLException e) { log.error(e,e); } finally { try { rset.close(); } catch ( Exception e) { } try { stmt.close(); } catch ( Exception e) { } try { conn.close(); } catch ( Exception e) { } } if (ir != null) localImgs.put(rftId,ir); } return ir; }
Example 33
From project ChkBugReport, under directory /src/com/sonyericsson/chkbugreport/doc/.
Source file: Table.java

private void dbCreate(){ if (mConn == null) { return; } try { Statement stat=mConn.createStatement(); StringBuffer sqlCreate=new StringBuffer(); StringBuffer sqlInsert=new StringBuffer(); sqlCreate.append("CREATE TABLE "); sqlCreate.append(mTable); sqlCreate.append(" ("); sqlInsert.append("INSERT INTO "); sqlInsert.append(mTable); sqlInsert.append(" VALUES ("); for (int i=0; i < mColumns.size(); i++) { if (i > 0) { sqlCreate.append(","); sqlInsert.append(","); } sqlCreate.append(mColumns.get(i).dbSpec); sqlInsert.append("?"); } sqlCreate.append(")"); sqlInsert.append(")"); stat.execute(sqlCreate.toString()); mSqlInsert=mConn.prepareStatement(sqlInsert.toString()); } catch ( SQLException e) { e.printStackTrace(); dbAbort(); } }
Example 34
From project CloudReports, under directory /src/main/java/cloudreports/database/.
Source file: Database.java

/** * Creates a brand new database. * @see #connection * @since 1.0 */ public static void createDatabase(){ try { establishConnection(); Statement stat=connection.createStatement(); createCustomersTable(stat); createDatacentersTable(stat); createHostsTable(stat); createSanStorageTable(stat); createUtilizationProfilesTable(stat); createVirtualMachinesTable(stat); createNetworkMapTable(stat); createReportDataTable(stat); createMigrationsTable(stat); createSettingsTable(stat); createRandomPoolTable(stat); insertDefaultSettingsValues(stat); } catch ( Exception ex) { Dialog.showErrorMessage(new JFrame(),"An error occurred while creating the database."); System.exit(0); } finally { closeConnection(connection); } }
Example 35
From project archaius, under directory /archaius-core/src/main/java/com/netflix/config/sources/.
Source file: JDBCConfigurationSource.java

/** * Close a <code>Connection</code> and, <code>Statement</code>. Avoid closing if null and hide any SQLExceptions that occur. * @param conn The database connection to close * @param stmt The statement to close */ private void close(Connection conn,Statement stmt,ResultSet rs){ try { if (rs != null) { rs.close(); } } catch ( SQLException e) { log.error("An error occured on closing the ResultSet",e); } try { if (stmt != null) { stmt.close(); } } catch ( SQLException e) { log.error("An error occured on closing the statement",e); } try { if (conn != null) { conn.close(); } } catch ( SQLException e) { log.error("An error occured on closing the connection",e); } }