Java Code Examples for java.sql.Connection.close()

The following are Jave code examples for showing how to use close() of the java.sql.Connection class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: azeroth   File: JDBCUtils.java   View Source Code Vote up 7 votes
/**
 * Close connection
 *
 * @param rs
 */
public static void close(ResultSet rs) {
    Statement st = null;
    Connection con = null;
    try {
        try {
            if (rs != null) {
                st = rs.getStatement();
                rs.close();
            }
        } finally {
            try {
                if (st != null) {
                    con = st.getConnection();
                    st.close();
                }
            } finally {
                if (con != null) {
                    con.close();
                }
            }
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
}
 
Example 2
Project: ProyectoPacientes   File: MetaDataRegressionTest.java   View Source Code Vote up 6 votes
/**
 * Tests fix for BUG#12975 - OpenOffice expects DBMD.supportsIEF() to return
 * "true" if foreign keys are supported by the datasource, even though this
 * method also covers support for check constraints, which MySQL _doesn't_
 * have.
 * 
 * @throws Exception
 *             if the test fails.
 */
public void testBug12975() throws Exception {
    assertEquals(false, this.conn.getMetaData().supportsIntegrityEnhancementFacility());

    Connection overrideConn = null;

    try {
        Properties props = new Properties();

        props.setProperty("overrideSupportsIntegrityEnhancementFacility", "true");

        overrideConn = getConnectionWithProps(props);
        assertEquals(true, overrideConn.getMetaData().supportsIntegrityEnhancementFacility());
    } finally {
        if (overrideConn != null) {
            overrideConn.close();
        }
    }
}
 
Example 3
Project: spr   File: SqlDelete.java   View Source Code Vote up 6 votes
public static void deleteTipoObjetivo(String id){
 	 Connection conect=ConnectionConfiguration.conectar();
 	 Statement statement = null;
 String 				query = "delete from tipo_objetivo ";
 //if (id!="")			query+= "id=\""+id+"\", ";
 /*if (nombre!="")		query+= "nombre=\""+nombre+"\", ";
 if (descripcion!="")	query+= "descripcion=\""+descripcion+"\", ";
 query = query.substring(0, query.length()-2);*/
 query+="where id="+id;
		
try {
	statement=conect.createStatement();
	statement.execute(query);
    conect.close();
} catch (SQLException e) {e.printStackTrace();}
 }
 
Example 4
Project: legendarybot   File: IGuildSettings.java   View Source Code Vote up 6 votes
/**
 * Create a {@link GuildSettings} instance
 * @param guild The Guild those settings are being linked to.
 * @param bot A {@link LegendaryBot} instance.
 */
public IGuildSettings(Guild guild, LegendaryBot bot) {
    this.bot = bot;
    this.guildId = guild.getId();
    try {
        Connection conn = bot.getDatabase().getConnection();
        PreparedStatement statement = conn.prepareStatement("SELECT configName,configValue FROM guild_config WHERE guildId=?");
        statement.setString(1, guildId);
        ResultSet set = statement.executeQuery();
        while (set.next()) {
            settings.put(set.getString("configName"),set.getString("configValue"));
        }
        set.close();
        statement.close();
        conn.close();
    } catch (SQLException e) {
        e.printStackTrace();
        bot.getStacktraceHandler().sendStacktrace(e, "guildId:" + guildId);
    }
}
 
Example 5
Project: tcp   File: SqlUpdates.java   View Source Code Vote up 6 votes
public static boolean borradoAvanceCosto(AvanceCosto objeto, String usuarioResponsable){
  	 Connection conect=ConnectionConfiguration.conectar();
  	 Statement statement = null;
  	 objeto.changeBorrado();
  	 
	 String query = "update avance_costo set borrado='"+objeto.isBorrado()+"'";
	 		query += ", usuario_responsable='" + usuarioResponsable + "'";
	 		 
		 query+=" where id ="+objeto.getId();
	 
	 try {
		statement=conect.createStatement();
		statement.execute(query);
	    conect.close();
	    return true;
	 }catch (SQLException e) {e.printStackTrace(); return false;}
}
 
Example 6
Project: spr   File: SqlHelper.java   View Source Code Vote up 6 votes
public static void insertFuenteFinanciamietno(int numero_fila,int anho,int id,String nombre, String descripcion){
 	 Connection conect=conectar();
 String query = " insert into fuente_financiamiento (numero_fila,anho,id,nombre,descripcion)"
	        + " values (?,?,?,?,?)";
try {
	
	PreparedStatement preparedStmt;
	preparedStmt = conect.prepareStatement(query);
	preparedStmt.setInt (1, numero_fila);
	preparedStmt.setInt (2,anho);
	preparedStmt.setInt (3, id);
	preparedStmt.setString (4, nombre);
	preparedStmt.setString (5, descripcion);
    preparedStmt.execute();
    conect.close();
} catch (SQLException e) {e.printStackTrace();}
 }
 
Example 7
Project: tcp   File: SqlHelper.java   View Source Code Vote up 6 votes
public static void insertPilares(int id,  String nombre, String descripcion, int numero_fila, int eje, int linea){
 	 Connection conect=conectar();
 String query = " insert into estrategia (id, nombre, descripcion, numero_fila, eje_estrategico_id,  linea_transversal_id)"
	        + " values (?,?,?,?,?,?)";
try {
	
	PreparedStatement preparedStmt;
	preparedStmt = conect.prepareStatement(query);
	preparedStmt.setInt (1, id);
	preparedStmt.setString (2, nombre);
	preparedStmt.setString (3, descripcion);
	preparedStmt.setInt (4, numero_fila);
	preparedStmt.setInt (5, eje);
	preparedStmt.setInt (6, linea);
    preparedStmt.execute();
    conect.close();
} catch (SQLException e) {e.printStackTrace();}
 }
 
Example 8
Project: the-vigilantes   File: StatementRegressionTest.java   View Source Code Vote up 6 votes
public void testBug40439() throws Exception {
    Connection conn2 = null;
    try {
        createTable("testBug40439VALUES", "(x int)");
        conn2 = getConnectionWithProps("rewriteBatchedStatements=true");
        PreparedStatement ps = conn2.prepareStatement("insert into testBug40439VALUES (x) values (?)");
        ps.setInt(1, 1);
        ps.addBatch();
        ps.setInt(1, 2);
        ps.addBatch();
        ps.executeBatch();
    } finally {
        if (conn2 != null) {
            try {
                conn2.close();
            } catch (SQLException ex) {
            }
        }
    }
}
 
Example 9
Project: OpenVertretung   File: StatementRegressionTest.java   View Source Code Vote up 6 votes
/**
 * Tests fix for BUG#54095 - Unnecessary call in newSetTimestampInternal.
 *
 * This bug was fixed as a consequence of the patch for Bug#71084.
 *
 * @throws Exception
 *             if the test fails.
 */
public void testBug54095() throws Exception {
    Connection testConn = getConnectionWithProps("useLegacyDatetimeCode=false");

    Calendar testCal = Calendar.getInstance();
    java.util.Date origDate = testCal.getTime();

    PreparedStatement testPstmt = testConn.prepareStatement("SELECT ?");
    testPstmt.setTimestamp(1, new Timestamp(0), testCal);
    assertEquals("Calendar object shouldn't have changed after PreparedStatement.setTimestamp().", origDate, testCal.getTime());

    ResultSet testRs = testPstmt.executeQuery();
    testRs.next();
    assertEquals("Calendar object shouldn't have changed after PreparedStatement.executeQuery().", origDate, testCal.getTime());

    testRs.getTimestamp(1, testCal);
    assertEquals("Calendar object shouldn't have changed after ResultSet.getTimestamp().", origDate, testCal.getTime());

    testRs.close();
    testPstmt.close();
    testConn.close();
}
 
Example 10
Project: spring-boot-data-source-decorator   File: TracingQueryExecutionListenerTests.java   View Source Code Vote up 6 votes
@Test
public void testShouldAddSpanForPreparedStatementExecuteUpdate() throws Exception {
    Connection connection = dataSource.getConnection();
    connection.prepareStatement("UPDATE INFORMATION_SCHEMA.TABLES SET table_Name = '' WHERE 0 = 1").executeUpdate();
    connection.close();

    assertThat(ExceptionUtils.getLastException()).isNull();

    assertThat(spanReporter.getSpans()).hasSize(2);
    Span connectionSpan = spanReporter.getSpans().get(0);
    Span statementSpan = spanReporter.getSpans().get(1);
    assertThat(connectionSpan.getName()).isEqualTo("jdbc:/dataSource/connection");
    assertThat(statementSpan.getName()).isEqualTo("jdbc:/dataSource/query");
    assertThat(statementSpan.tags()).containsEntry(SleuthListenerAutoConfiguration.SPAN_SQL_QUERY_TAG_NAME, "UPDATE INFORMATION_SCHEMA.TABLES SET table_Name = '' WHERE 0 = 1");
    assertThat(statementSpan.tags()).containsEntry(SleuthListenerAutoConfiguration.SPAN_ROW_COUNT_TAG_NAME, "0");
}
 
Example 11
Project: bdf2   File: ExcelModelManager.java   View Source Code Vote up 6 votes
public List<String> findAllTables(String dataSourceName) throws Exception {
	List<String> tablesList = new ArrayList<String>();
	Connection conn = null;
	ResultSet rs = null;
	try {
		conn = connectionHelper.getConnection(dataSourceName);
		DatabaseMetaData metaData = conn.getMetaData();
		String url = metaData.getURL();
		String schema = null;
		if (url.toLowerCase().contains("oracle")) {
			schema = metaData.getUserName();
		}
		rs = metaData.getTables(null, schema, "%", new String[] { "TABLE" });
		while (rs.next()) {
			tablesList.add(rs.getString("TABLE_NAME").toLowerCase());
		}
		return tablesList;
	} finally {
		if (conn != null) {
			conn.close();
		}
		if (rs != null) {
			rs.close();
		}
	}
}
 
Example 12
Project: tangyuan2   File: DBCPDataSource.java   View Source Code Vote up 5 votes
@Override
public void recycleConnection(Connection connection) throws SQLException {
	try {
		connection.close();
	} catch (Exception e) {
		log.error("recycleConnection exception", e);
	}
}
 
Example 13
Project: tcp   File: SqlUpdates.java   View Source Code Vote up 5 votes
public static boolean actAvanceCosto(AvanceCosto objeto, String usuarioResponsable){
 try {
	 Connection conect=ConnectionConfiguration.conectar();
	 String query = "update avance_costo set ";
	 PreparedStatement update =null;

	 	if(objeto.getMonto()!=0) 				query+= "monto= ?";
		if(objeto.getCodigoContratacion()!=null)query+= ", codigo_contratacionl= ?";
		if(objeto.getObjetoGasto()!=0)  		query+= ", objeto_gasto= ?";
		if(objeto.getAvanceId()!=0)      		query+= ", avance_id= ?";
												query += ", usuario_responsable = ? ";

		query+=" where id = ?";

		int cantCampos =0;
		update = conect.prepareStatement(query);
		if (objeto.getMonto()!=0) 					{    cantCampos++;update.setDouble (cantCampos, objeto.getMonto());}
		if (objeto.getCodigoContratacion()!=null)	{    cantCampos++;update.setString (cantCampos, objeto.getCodigoContratacion());}
		if (objeto.getObjetoGasto()!=0)     		{    cantCampos++;update.setInt (cantCampos, objeto.getObjetoGasto());}
		if (objeto.getAvanceId()!=0)        		{    cantCampos++;update.setInt	(cantCampos, objeto.getAvanceId());}
				
			cantCampos++;
			update.setString (cantCampos, usuarioResponsable);
		
            cantCampos++;
            update.setInt    (cantCampos , objeto.getId());

            update.execute();
			conect.close();
	    return true;
	} catch (SQLException e) {e.printStackTrace(); return false;}
}
 
Example 14
Project: L2jBrasil   File: L2Clan.java   View Source Code Vote up 5 votes
/**
 * @return Returns the noticeEnabled.
 */
public boolean isNoticeEnabled()
{
 String result="";
 Connection con = null;
 try
 {
    
	 con = L2DatabaseFactory.getInstance().getConnection();
	 PreparedStatement statement = con.prepareStatement("SELECT enabled FROM clan_notices WHERE clanID=?");
	 statement.setInt(1, getClanId());
	 ResultSet rset = statement.executeQuery();
    
	 while (rset.next())
	 {
		 result = rset.getString("enabled");
	 }
    
	 rset.close();
	 statement.close();
	 con.close();
    
 } catch (Exception e)
 {
	 if (Config.DEBUG)
	 System.out.println("BBS: Error while reading _noticeEnabled for clan "+ this.getClanId() + "");
	 if(e.getMessage()!=null)
		 if (Config.DEBUG) 
		 System.out.println("BBS: Exception = "+e.getMessage()+"");
 }
 if (result.isEmpty())
 {
	 insertNotice();
	 return false;
 }
 else if(result.compareToIgnoreCase("true")==0)
	 return true;
 else
	 return false;
}
 
Example 15
Project: Lagerta   File: JDBCUtil.java   View Source Code Vote up 5 votes
public static void executeUpdateQueryFromResource(Connection connection, String resourceName) {
    URL resource = JDBCUtil.class.getResource(resourceName);
    try {
        String query = Resources.toString(resource, Charsets.UTF_8);
        try (Statement statement = connection.createStatement()) {
            statement.executeUpdate(query);
        }
        connection.close();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 16
Project: the-vigilantes   File: ConnectionRegressionTest.java   View Source Code Vote up 5 votes
public void testBug35660() throws Exception {

        Connection lbConn = getLoadBalancedConnection(null);
        Connection lbConn2 = getLoadBalancedConnection(null);

        try {
            assertEquals(this.conn, this.conn);
            assertEquals(lbConn, lbConn);
            assertFalse(lbConn.equals(this.conn));
            assertFalse(lbConn.equals(lbConn2));
        } finally {
            lbConn.close();
            lbConn2.close();
        }
    }
 
Example 17
Project: spr   File: SqlSelects.java   View Source Code Vote up 5 votes
public static List<Documentos> selectAllDocumento(String condicion) throws SQLException  {
	Connection conect = ConnectionConfiguration.conectar();
	String query = " select * from documentos " + condicion;
				
	Statement statement = null;
	ResultSet rs = null;
	List<Documentos> objetos = new ArrayList<Documentos>();
	try {
		statement = conect.createStatement();
		rs = statement.executeQuery(query);
		while (rs.next()) {
			Documentos objeto = new Documentos();
				
			objeto.setId(rs.getInt("id"));
			objeto.setNombre(rs.getString("nombre"));
  				objeto.setUrl(getFileName(rs.getString("url")));
			objeto.setDescripcion(rs.getString("descripcion"));
			objeto.setBorrado(rs.getBoolean("borrado"));
			objeto.setFecha(rs.getString("fecha_valides"));
			objeto.setTipoId(rs.getInt("tipos_id"));
			objeto.setUsuarioResponsable(rs.getString("usuario_responsable"));
				
			objetos.add(objeto);
		}
	} catch (SQLException e) {
		e.printStackTrace();
	} finally {
		if (statement != null) {
			statement.close();
		}
		if (conect != null) {
			conect.close();
		}
	}
	return objetos;
}
 
Example 18
Project: oscm   File: TestDBSetup.java   View Source Code Vote up 5 votes
static void loadSchema(final DataSource datasource, String scriptDir,
        final DatabaseVersionInfo toVersion, String dbType)
        throws Exception {
    Connection connection = datasource.getConnection();
    DatabaseUpgradeHandler handler = new DatabaseUpgradeHandler();
    handler.performUpgrade(connection, scriptDir, toVersion, dbType,
            new PrintStream(new DevNul()));
    connection.close();
}
 
Example 19
Project: the-vigilantes   File: ConnectionRegressionTest.java   View Source Code Vote up 4 votes
/**
 * Tests fix for BUG#6966, connections starting up failed-over (due to down
 * master) never retry master.
 * 
 * @throws Exception
 *             if the test fails...Note, test is timing-dependent, but
 *             should work in most cases.
 */
public void testBug6966() throws Exception {
    Properties props = new Driver().parseURL(BaseTestCase.dbUrl, null);
    props.setProperty("autoReconnect", "true");
    props.setProperty("socketFactory", "testsuite.UnreliableSocketFactory");

    Properties urlProps = new NonRegisteringDriver().parseURL(dbUrl, null);

    String host = urlProps.getProperty(NonRegisteringDriver.HOST_PROPERTY_KEY);
    String port = urlProps.getProperty(NonRegisteringDriver.PORT_PROPERTY_KEY);

    props.remove(NonRegisteringDriver.HOST_PROPERTY_KEY);
    props.remove(NonRegisteringDriver.NUM_HOSTS_PROPERTY_KEY);
    props.remove(NonRegisteringDriver.HOST_PROPERTY_KEY + ".1");
    props.remove(NonRegisteringDriver.PORT_PROPERTY_KEY + ".1");

    props.setProperty("queriesBeforeRetryMaster", "50");
    props.setProperty("maxReconnects", "1");

    UnreliableSocketFactory.mapHost("master", host);
    UnreliableSocketFactory.mapHost("slave", host);
    UnreliableSocketFactory.downHost("master");

    Connection failoverConnection = null;

    try {
        failoverConnection = getConnectionWithProps("jdbc:mysql://master:" + port + ",slave:" + port + "/", props);
        failoverConnection.setAutoCommit(false);

        String originalConnectionId = getSingleIndexedValueWithQuery(failoverConnection, 1, "SELECT CONNECTION_ID()").toString();

        for (int i = 0; i < 50; i++) {
            this.rs = failoverConnection.createStatement().executeQuery("SELECT 1");
        }

        UnreliableSocketFactory.dontDownHost("master");

        failoverConnection.setAutoCommit(true);

        String newConnectionId = getSingleIndexedValueWithQuery(failoverConnection, 1, "SELECT CONNECTION_ID()").toString();

        assertEquals("/master", UnreliableSocketFactory.getHostFromLastConnection());
        assertFalse(newConnectionId.equals(originalConnectionId));

        this.rs = failoverConnection.createStatement().executeQuery("SELECT 1");
    } finally {
        UnreliableSocketFactory.flushAllStaticData();

        if (failoverConnection != null) {
            failoverConnection.close();
        }
    }
}
 
Example 20
Project: the-vigilantes   File: StringRegressionTest.java   View Source Code Vote up 4 votes
/**
 * Tests fix for BUG#11614 - StringUtils.getBytes() doesn't work when using
 * multibyte character encodings and a length in _characters_ is specified.
 * 
 * @throws Exception
 *             if the test fails.
 */
public void testBug11614() throws Exception {
    if (versionMeetsMinimum(4, 1)) {
        createTable("testBug11614",
                "(`id` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT, `text` TEXT NOT NULL," + "PRIMARY KEY(`id`)) CHARACTER SET utf8 COLLATE utf8_general_ci");

        Properties props = new Properties();
        props.setProperty("characterEncoding", "utf8");

        Connection utf8Conn = null;

        try {
            utf8Conn = getConnectionWithProps(props);

            utf8Conn.createStatement().executeUpdate("INSERT INTO testBug11614  (`id`,`text`) values (1,'')");
            this.rs = utf8Conn.createStatement().executeQuery("SELECT `text` FROM testBug11614 WHERE id=1");
            assertTrue(this.rs.next());

            Clob c = this.rs.getClob(1);
            c.truncate(0);
            int blockSize = 8192;
            int sizeToTest = blockSize + 100;

            StringBuilder blockBuf = new StringBuilder(sizeToTest);

            for (int i = 0; i < sizeToTest; i++) {
                blockBuf.append('\u00f6');
            }

            String valueToTest = blockBuf.toString();

            c.setString(1, valueToTest);
            this.pstmt = utf8Conn.prepareStatement("UPDATE testBug11614 SET `text` = ? WHERE id=1");
            this.pstmt.setClob(1, c);
            this.pstmt.executeUpdate();
            this.pstmt.close();

            String fromDatabase = getSingleIndexedValueWithQuery(utf8Conn, 1, "SELECT `text` FROM testBug11614").toString();
            assertEquals(valueToTest, fromDatabase);
        } finally {
            if (utf8Conn != null) {
                utf8Conn.close();
            }

        }
    }
}