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

The following are Jave code examples for showing how to use close() of the java.sql.Statement class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: OpenDiabetes   File: Testdb.java   Source Code and License Vote up 6 votes
public synchronized void query(String expression) throws SQLException {

        Statement st = null;
        ResultSet rs = null;

        st = conn.createStatement();         // statement objects can be reused with

        // repeated calls to execute but we
        // choose to make a new one each time
        rs = st.executeQuery(expression);    // run the query

        // do something with the result set.
        dump(rs);
        st.close();    // NOTE!! if you close a statement the associated ResultSet is

        // closed too
        // so you should copy the contents to some other object.
        // the result set is invalidated also  if you recycle an Statement
        // and try to execute some other query before the result set has been
        // completely examined.
    }
 
Example 2
Project: spr   File: SqlSelects.java   Source Code and License Vote up 6 votes
public static List<ObjetivoSugerido> selectAllObjetivoSugerido(String condition) throws SQLException{
	Connection conect=ConnectionConfiguration.conectar();
	String query = " select * from objetivo_sugerido "+condition;
	
	Statement statement = null;
	ResultSet rs=null;
	List<ObjetivoSugerido> objetos = new ArrayList<ObjetivoSugerido>();
	try {
	statement = conect.createStatement();
	rs=statement.executeQuery(query);
		while(rs.next()){
			ObjetivoSugerido objeto = new ObjetivoSugerido();
		
			objeto.setObjetivoId(rs.getInt("objetivo_id"));
			objeto.setTipoObjetivoId(rs.getInt("objetivo_tipo_objetivo_id"));
			objeto.setObjetivoAnho(rs.getInt("objetivo_anho"));
			objeto.setObjetivoVersion(rs.getInt("objetivo_version"));
			objeto.setObjetivoSugeridoId(rs.getInt("objetivo_sugerido_id"));
			objeto.setObjetivoSugeridoTipoId(rs.getInt("objetivo_sugerido_tipo_id"));
			objeto.setObjetivoSugeridoAnho(rs.getInt("objetivo_sugerido_anho"));
			objeto.setObjetivoSugeridoVersion(rs.getInt("objetivo_sugerido_version"));
			objeto.setBorrado((rs.getBoolean("borrado")));

			objetos.add(objeto);
		}
	}
	catch (SQLException e) {e.printStackTrace();}
	finally{
	if (statement != null) {statement.close();}
	if (conect != null) {conect.close();}
	}
return objetos;
}
 
Example 3
Project: spr   File: SqlSelects.java   Source Code and License Vote up 6 votes
public static List<PlanEje> selectAllPLanEje() throws SQLException{
 	 	Connection conect=ConnectionConfiguration.conectar();String query = " select * from eje_estrategico";
 Statement statement = null; ResultSet rs=null;
 List<PlanEje> objetos = new ArrayList<PlanEje>();

try {
	statement = conect.createStatement();
	rs=statement.executeQuery(query);
	
	while(rs.next()){
		PlanEje objeto = new PlanEje();
		objeto.setEjeNombre(rs.getString("nombre"));
		objeto.setEjeDescripcion(rs.getString("descripcion"));
		objeto.setCodigoPlan(rs.getShort("plan_id"));
		objeto.setEjeCodigo(rs.getShort("id"));
		objetos.add(objeto);
	}
}
catch (SQLException e) {e.printStackTrace();}
finally{
	if (statement != null) {statement.close();}
	if (conect != null) {conect.close();}
}
return objetos;
 }
 
Example 4
Project: ProyectoPacientes   File: StatementRegressionTest.java   Source Code and License Vote up 6 votes
/**
 * Tests fix for Bug#44056 - Statement.getGeneratedKeys() retains result set
 * instances until statement is closed.
 */

public void testBug44056() throws Exception {
    createTable("testBug44056", "(pk int primary key not null auto_increment)");
    Statement newStmt = this.conn.createStatement();

    try {
        newStmt.executeUpdate("INSERT INTO testBug44056 VALUES (null)", Statement.RETURN_GENERATED_KEYS);
        checkOpenResultsFor44056(newStmt);
        this.pstmt = this.conn.prepareStatement("INSERT INTO testBug44056 VALUES (null)", Statement.RETURN_GENERATED_KEYS);
        this.pstmt.executeUpdate();
        checkOpenResultsFor44056(this.pstmt);
        this.pstmt = ((com.mysql.jdbc.Connection) this.conn).serverPrepareStatement("INSERT INTO testBug44056 VALUES (null)",
                Statement.RETURN_GENERATED_KEYS);
        this.pstmt.executeUpdate();
        checkOpenResultsFor44056(this.pstmt);
    } finally {
        newStmt.close();
    }
}
 
Example 5
Project: tcp   File: SqlSelects.java   Source Code and License Vote up 6 votes
public static List<Rol> selectRoles(String condition) throws SQLException{
 	 Connection conect=ConnectionConfiguration.conectarSpr();
 String query = " select * from role " + condition;
 
 Statement statement = null;
 ResultSet rs=null;
 List<Rol> objetos = new ArrayList<Rol>();

try {
	statement = conect.createStatement();
	rs=statement.executeQuery(query);
	while(rs.next()){
		Rol objeto = new Rol();
		objeto.setRolId(rs.getInt("id"));
		objeto.setNombre(rs.getString("nombre"));

		objetos.add(objeto);
	}
}
catch (SQLException e) {e.printStackTrace();}
finally{
	if (statement != null) {statement.close();}
	if (conect != null) {conect.close();}
}
return objetos; 
}
 
Example 6
Project: server   File: DatabaseHelper.java   Source Code and License Vote up 5 votes
/**
 * Update indexes
 *
 * @param connection
 *            data connection
 */
public static void analyze(ConnectionProxy connection) throws DataAccessException {

	try {

		Statement statement = connection.getConnection().createStatement();
		statement.executeUpdate("PRAGMA optimize;");
		statement.close();

	} catch (Exception e) {
		throw new DataAccessException(e);
	}

}
 
Example 7
Project: BibliotecaPS   File: ResultSetRegressionTest.java   Source Code and License Vote up 5 votes
/**
 * Tests fix for BUG#26173 - fetching rows via cursor retrieves corrupted
 * data.
 * 
 * @throws Exception
 *             if the test fails.
 */
public void testBug26173() throws Exception {
    if (!versionMeetsMinimum(5, 0)) {
        return;
    }

    createTable("testBug26173", "(fkey int, fdate date, fprice decimal(15, 2), fdiscount decimal(5,3))", "InnoDB");
    this.stmt.executeUpdate("insert into testBug26173 values (1, '2007-02-23', 99.9, 0.02)");

    Connection fetchConn = null;
    Statement stmtRead = null;

    Properties props = new Properties();
    props.setProperty("useServerPrepStmts", "true");
    props.setProperty("useCursorFetch", "true");

    try {

        fetchConn = getConnectionWithProps(props);
        stmtRead = fetchConn.createStatement();
        stmtRead.setFetchSize(1000);

        this.rs = stmtRead.executeQuery("select extract(year from fdate) as fyear, fprice * (1 - fdiscount) as fvalue from testBug26173");

        assertTrue(this.rs.next());
        assertEquals(2007, this.rs.getInt(1));
        assertEquals("97.90200", this.rs.getString(2));
    } finally {
        if (stmtRead != null) {
            stmtRead.close();
        }

        if (fetchConn != null) {
            fetchConn.close();
        }
    }
}
 
Example 8
Project: kibana_sourceforge   File: Load_Data.java   Source Code and License Vote up 5 votes
public static void main(String[] args) throws IOException {
    try {
        int max = 1000000;
        Connection connection = DriverManager.getConnection("jdbc:mysql://flossdata.syr.edu:3306", "username", "password");
        // Creates file
        BufferedWriter buffW = new BufferedWriter(Create_file());
        Statement stmt = (Statement) connection.createStatement();

        // Get projects from 2005
        String sql = "SELECT DISTINCT proj_unixname FROM sourceforge.sf_project_status";
        sql += " WHERE date_collected > '2005-01-01' "
                + "AND date_collected < '2005-12-12' "
                + "AND description != 'Inactive' LIMIT 10000;";
        ResultSet projectname = stmt.executeQuery(sql);
        System.out.println("Created project list!");

        if (projectname != null) {
            // Get number of projects
            projectname.last();
            int count = projectname.getRow();
            // Set project list to first position
            projectname.beforeFirst();
            int projectcount = 0;
            // Runs through all projects
            while (projectname.next()) {
                projectcount++;
                if (projectcount==2000)
                    break;
                System.out.println("Skip " + projectcount + " out of " + count);
            }

            while (projectname.next()) {
                projectcount++;
                System.out.println("Processing project " + projectcount + " out of " + count);
                projectname.getString(1);

                // Writes project details in file
                buffW.newLine();
                buffW.write("{\"index\":{\"_index\":\"projects\", \"_type\":\"project\", \"_id\": \"" + projectcount + "\"}}");
                buffW.newLine();
                buffW.write(read_attr(projectname.getString(1), connection));buffW.newLine();

                //Breaks if max is reached
                if (projectcount==max)
                    break;
            }
        }
        //Closes all connections
        buffW.close();
        stmt.close();
        connection.close();
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
}
 
Example 9
Project: uavstack   File: TestRestService.java   Source Code and License Vote up 5 votes
@GET
@Path("testDBCP2")
public void testDBCP2() {

    if (bds2 == null) {
        bds2 = new org.apache.commons.dbcp2.BasicDataSource();
        bds2.setUrl("jdbc:mysql://127.0.0.1:3306/testdb");
        bds2.setUsername("root");
        bds2.setPassword("root");
        bds2.setDriverClassName("com.mysql.jdbc.Driver");
        bds2.setInitialSize(2);
        bds2.setMaxTotal(10);
        bds2.setMinIdle(0);
        bds2.setMaxIdle(1);
        bds2.setMaxWaitMillis(30000);
        bds2.setMaxOpenPreparedStatements(20);
    }

    try {
        Connection c = bds2.getConnection();

        Statement st = c.createStatement();

        st.execute("insert into mytest values (1,'zz',23)");

        st.executeQuery("select name from mytest where id=1");

        st.executeUpdate("update mytest set age=24 where id=1");

        st.executeUpdate("delete from mytest where id=1");

        st.close();

        c.close();
    }
    catch (Exception e) {

    }
}
 
Example 10
Project: ProyectoPacientes   File: ResultSetRegressionTest.java   Source Code and License Vote up 5 votes
/**
 * Tests that streaming result sets are registered correctly.
 * 
 * @throws Exception
 *             if any errors occur
 */
public void testClobberStreamingRS() throws Exception {
    try {
        Properties props = new Properties();
        props.setProperty("clobberStreamingResults", "true");

        Connection clobberConn = getConnectionWithProps(props);

        Statement clobberStmt = clobberConn.createStatement();

        clobberStmt.executeUpdate("DROP TABLE IF EXISTS StreamingClobber");
        clobberStmt.executeUpdate("CREATE TABLE StreamingClobber ( DUMMYID INTEGER NOT NULL, DUMMYNAME VARCHAR(32),PRIMARY KEY (DUMMYID) )");
        clobberStmt.executeUpdate("INSERT INTO StreamingClobber (DUMMYID, DUMMYNAME) VALUES (0, NULL)");
        clobberStmt.executeUpdate("INSERT INTO StreamingClobber (DUMMYID, DUMMYNAME) VALUES (1, 'nro 1')");
        clobberStmt.executeUpdate("INSERT INTO StreamingClobber (DUMMYID, DUMMYNAME) VALUES (2, 'nro 2')");
        clobberStmt.executeUpdate("INSERT INTO StreamingClobber (DUMMYID, DUMMYNAME) VALUES (3, 'nro 3')");

        Statement streamStmt = null;

        try {
            streamStmt = clobberConn.createStatement(java.sql.ResultSet.TYPE_FORWARD_ONLY, java.sql.ResultSet.CONCUR_READ_ONLY);
            streamStmt.setFetchSize(Integer.MIN_VALUE);

            this.rs = streamStmt.executeQuery("SELECT DUMMYID, DUMMYNAME FROM StreamingClobber ORDER BY DUMMYID");

            this.rs.next();

            // This should proceed normally, after the driver clears the input stream
            ResultSet rs2 = clobberStmt.executeQuery("SHOW VARIABLES");
            rs2.next();
            this.rs.close();
        } finally {
            if (streamStmt != null) {
                streamStmt.close();
            }
        }
    } finally {
        this.stmt.executeUpdate("DROP TABLE IF EXISTS StreamingClobber");
    }
}
 
Example 11
Project: BibliotecaPS   File: ConnectionRegressionTest.java   Source Code and License Vote up 5 votes
private void testBug18869381WithProperties(Properties props) throws Exception {
    Connection testConn = null;
    Statement testSt = null;
    ResultSet testRs = null;

    try {
        testConn = getConnectionWithProps(sha256Url, props);

        ((MySQLConnection) testConn).changeUser("bug18869381user1", "LongLongLongLongLongLongLongLongLongLongLongLongPwd1");
        testSt = testConn.createStatement();
        testRs = testSt.executeQuery("select USER(),CURRENT_USER()");
        testRs.next();
        assertEquals("bug18869381user1", testRs.getString(1).split("@")[0]);
        assertEquals("bug18869381user1", testRs.getString(2).split("@")[0]);
        testSt.close();

        ((MySQLConnection) testConn).changeUser("bug18869381user2", "pwd2");
        testSt = testConn.createStatement();
        testRs = testSt.executeQuery("select USER(),CURRENT_USER()");
        testRs.next();
        assertEquals("bug18869381user2", testRs.getString(1).split("@")[0]);
        assertEquals("bug18869381user2", testRs.getString(2).split("@")[0]);
        testSt.close();

        ((MySQLConnection) testConn).changeUser("bug18869381user3", "pwd3");
        testSt = testConn.createStatement();
        testRs = testSt.executeQuery("select USER(),CURRENT_USER()");
        testRs.next();
        assertEquals("bug18869381user3", testRs.getString(1).split("@")[0]);
        assertEquals("bug18869381user3", testRs.getString(2).split("@")[0]);

    } finally {
        if (testConn != null) {
            testConn.close();
        }
    }
}
 
Example 12
Project: OpenVertretung   File: ResultSetRegressionTest.java   Source Code and License Vote up 5 votes
/**
 * Tests fix for BUG#13374 - ResultSet.getStatement() on closed result set
 * returns NULL (as per JDBC 4.0 spec, but not backwards-compatible).
 * 
 * @throws Exception
 *             if the test fails
 */

public void testBug13374() throws Exception {
    Statement retainStmt = null;
    Connection retainConn = null;

    try {
        Properties props = new Properties();

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

        retainConn = getConnectionWithProps(props);

        retainStmt = retainConn.createStatement();

        this.rs = retainStmt.executeQuery("SELECT 1");
        this.rs.close();
        assertNotNull(this.rs.getStatement());

        this.rs = this.stmt.executeQuery("SELECT 1");
        this.rs.close();

        try {
            this.rs.getStatement();
        } catch (SQLException sqlEx) {
            assertEquals(sqlEx.getSQLState(), SQLError.SQL_STATE_GENERAL_ERROR);
        }

    } finally {

        if (retainStmt != null) {
            retainStmt.close();
        }

        if (retainConn != null) {
            retainConn.close();
        }
    }
}
 
Example 13
Project: tcp   File: SqlSelects.java   Source Code and License Vote up 5 votes
public static List<Etiqueta> selectEtiqueta() throws SQLException{
 	 Connection conect=ConnectionConfiguration.conectar();
 String query = " select * from etiqueta";
 
 Statement statement = null;
 ResultSet rs=null;
 List<Etiqueta> objetos = new ArrayList<Etiqueta>();

try {
	statement = conect.createStatement();
	rs=statement.executeQuery(query);
	while(rs.next()){
		Etiqueta objeto = new Etiqueta();
		objeto.setId(rs.getInt("id"));
		objeto.setNombre(rs.getString("nombre"));
		objeto.setDescripcion(rs.getString("descripcion"));
		objeto.setBorrado(rs.getBoolean("borrado"));

		objetos.add(objeto);
	}
}
catch (SQLException e) {e.printStackTrace();}
finally{
	if (statement != null) {statement.close();}
	if (conect != null) {conect.close();}
}
return objetos; 
}
 
Example 14
Project: gretl   File: CsvExportTest.java   Source Code and License Vote up 5 votes
@Test
public void exportOk() throws Exception {
    String schemaName = "csvexport".toLowerCase();
    Connection con = null;
    try{
        con = TestUtilSql.connectPG();
        TestUtilSql.createOrReplaceSchema(con, schemaName);
        Statement s1 = con.createStatement();
        s1.execute("CREATE TABLE "+schemaName+".exportdata(t_id serial, \"Aint\" integer, adec decimal(7,1), atext varchar(40), aenum varchar(120),adate date, atimestamp timestamp, aboolean boolean, aextra varchar(40))");
        s1.execute("INSERT INTO "+schemaName+".exportdata(t_id, \"Aint\", adec, atext, adate, atimestamp, aboolean) VALUES (1,2,3.4,'abc','2013-10-21','2015-02-16T08:35:45.000','true')");
        s1.execute("INSERT INTO "+schemaName+".exportdata(t_id) VALUES (2)");
        s1.close();
        TestUtilSql.grantDataModsInSchemaToUser(con, schemaName, TestUtilSql.PG_CON_DMLUSER);

        con.commit();
        TestUtilSql.closeCon(con);

        GradleVariable[] gvs = {GradleVariable.newGradleProperty(TestUtilSql.VARNAME_PG_CON_URI, TestUtilSql.PG_CON_URI)};
        TestUtil.runJob("jobs/CsvExport", gvs);

        //check results
        System.out.println("cwd "+new File(".").getAbsolutePath());
        java.io.LineNumberReader reader=new java.io.LineNumberReader(new java.io.InputStreamReader(new java.io.FileInputStream(new File("jobs/CsvExport/data.csv"))));
        String line=reader.readLine();
           assertEquals("\"t_id\",\"Aint\",\"adec\",\"atext\",\"aenum\",\"adate\",\"atimestamp\",\"aboolean\"", line);
        line=reader.readLine();
           assertEquals("\"1\",\"2\",\"3.4\",\"abc\",\"\",\"2013-10-21\",\"2015-02-16T08:35:45.000\",\"true\"", line);
        line=reader.readLine();
           assertEquals("\"2\",\"\",\"\",\"\",\"\",\"\",\"\",\"\"", line);
        reader.close();
        
    }
    finally {
        TestUtilSql.closeCon(con);
    }
}
 
Example 15
Project: rapidminer   File: IndexCachedDatabaseExampleTable.java   Source Code and License Vote up 4 votes
protected void createRMPrimaryKeyIndex(DatabaseHandler databaseHandler, String tableName) throws SQLException {
    String addKeyQuery = "ALTER TABLE " + databaseHandler.getStatementCreator().makeIdentifier(tableName) + " ADD " + databaseHandler.getStatementCreator().makeIdentifier("RM_INDEX") + " INT NOT NULL AUTO_INCREMENT PRIMARY KEY";

    try {
        Statement ex = databaseHandler.createStatement(true, true);
        Throwable statement1 = null;

        try {
            ex.execute(addKeyQuery);
        } catch (Throwable var31) {
            statement1 = var31;
            throw var31;
        } finally {
            if(ex != null) {
                if(statement1 != null) {
                    try {
                        ex.close();
                    } catch (Throwable var30) {
                        statement1.addSuppressed(var30);
                    }
                } else {
                    ex.close();
                }
            }

        }
    } catch (SQLException var34) {
        addKeyQuery = "ALTER TABLE " + databaseHandler.getStatementCreator().makeIdentifier(tableName) + " ADD " + databaseHandler.getStatementCreator().makeIdentifier("RM_INDEX") + " INT NOT NULL IDENTITY(1,1) PRIMARY KEY";
        Statement statement = databaseHandler.createStatement(true, true);
        Throwable var6 = null;

        try {
            statement.execute(addKeyQuery);
        } catch (Throwable var29) {
            var6 = var29;
            throw var29;
        } finally {
            if(statement != null) {
                if(var6 != null) {
                    try {
                        statement.close();
                    } catch (Throwable var28) {
                        var6.addSuppressed(var28);
                    }
                } else {
                    statement.close();
                }
            }

        }
    }

}
 
Example 16
Project: OpenDiabetes   File: TestUpdatableResultSets.java   Source Code and License Vote up 4 votes
public void testDeletable2() {

        try {
            Connection c =
                DriverManager.getConnection("jdbc:hsqldb:mem:mytestdb", "SA",
                                            "");
            String createSQL =
                "create table test (num INTEGER PRIMARY KEY, str VARCHAR(25))";
            Statement createStmt = c.createStatement();

            createStmt.execute(createSQL);
            createStmt.close();

            String            ins = "insert into test (num,str) values (?,?)";
            PreparedStatement pStmt = c.prepareStatement(ins);

            for (int i = 0; i < 100; i++) {
                pStmt.setInt(1, i);
                pStmt.setString(2, "String" + i);
                pStmt.execute();
            }

            // there should now be 100 rows in the table
            String select = "SELECT * FROM test";
            PreparedStatement stmt = c.prepareStatement(select,
                ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
            ResultSet rs = stmt.executeQuery();

            rs.beforeFirst();

            while (rs.next()) {
                int num = rs.getInt("num");

                if ((num % 7) == 0) {
                    System.out.println("Deleting row:" + num);
                    rs.deleteRow();
                }
            }

            Statement dropStmt = c.createStatement();

            dropStmt.execute("drop table test;");
            dropStmt.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
 
Example 17
Project: testhelper   File: DBExecutor.java   Source Code and License Vote up 4 votes
private static void closeStatement(Statement stmt) {
	try {
		stmt.close();
	} catch (Exception ex) {
	}
}
 
Example 18
Project: dev-courses   File: TestBatchBug.java   Source Code and License Vote up 4 votes
static void reCreateTable(Connection con,
                              String tableAttr) throws SQLException {

        String cvsFileName = TEST_TABLE_NAME + ".csv";

// Create a statement object
        Statement stmt = con.createStatement();

// Try to drop the table
        try {

            stmt.executeUpdate("DROP TABLE " + TEST_TABLE_NAME + " IF EXISTS");
        } catch (SQLException e) {    // Ignore Exception, because the table may not yet exist
            System.out.println(e.getMessage());
        }

        StringBuffer sql = new StringBuffer();

        sql.append("CREATE ");
        sql.append(tableAttr);    // z.B. "CACHED"
        sql.append(" TABLE ");
        sql.append(TEST_TABLE_NAME);
        sql.append(" (");
        sql.append("Id integer IDENTITY");
        sql.append(", ");
        sql.append("Kennung varchar(20) NOT NULL");

// etwas andere Schreibweise von CURRENT TIMESTAMP
        sql.append(", last_update TIMESTAMP ");
        sql.append("DEFAULT CURRENT_TIMESTAMP NOT NULL");

        for (int i = 1; i <= DECIMAL_FIELDS_PER_DATASET; i++) {
            sql.append(", Field_" + i + " decimal");
        }

        sql.append(", UNIQUE(Kennung)");
        sql.append(")");
        System.out.println(sql.toString());
        stmt.executeUpdate(sql.toString());

// CLEAR TABLE
        sql = new StringBuffer();

        sql.append("DELETE FROM ");
        sql.append(TEST_TABLE_NAME);
        System.out.println(sql.toString());
        stmt.executeUpdate(sql.toString());
        stmt.close();    // is no longer used
    }
 
Example 19
Project: dremio-oss   File: Drill2489CallsAfterCloseThrowExceptionsTest.java   Source Code and License Vote up 4 votes
@BeforeClass
public static void setUpClosedObjects() throws Exception {
  // (Note: Can't use JdbcTest's connect(...) for this test class.)

  final Connection connToClose =
      new Driver().connect("jdbc:dremio:zk=local",
                           JdbcAssert.getDefaultProperties());
  final Connection connToKeep =
      new Driver().connect("jdbc:dremio:zk=local",
                           JdbcAssert.getDefaultProperties());

  final Statement plainStmtToClose = connToKeep.createStatement();
  final Statement plainStmtToKeep = connToKeep.createStatement();
  final PreparedStatement preparedStmtToClose =
      connToKeep.prepareStatement("VALUES 'PreparedStatement query'");
  try {
    connToKeep.prepareCall("VALUES 'CallableStatement query'");
    fail("Test seems to be out of date.  Was prepareCall(...) implemented?");
  }
  catch (SQLException | UnsupportedOperationException e) {
    // Expected.
  }

  final ResultSet resultSetToCloseOnStmtToClose =
      plainStmtToClose.executeQuery("VALUES 'plain Statement query'");
  resultSetToCloseOnStmtToClose.next();
  final ResultSet resultSetToCloseOnStmtToKeep =
      plainStmtToKeep.executeQuery("VALUES 'plain Statement query'");
  resultSetToCloseOnStmtToKeep.next();

  final ResultSetMetaData rsmdForClosedStmt =
      resultSetToCloseOnStmtToKeep.getMetaData();
  final ResultSetMetaData rsmdForOpenStmt =
      resultSetToCloseOnStmtToClose.getMetaData();

  final DatabaseMetaData dbmd = connToClose.getMetaData();

  connToClose.close();
  plainStmtToClose.close();
  preparedStmtToClose.close();
  resultSetToCloseOnStmtToClose.close();
  resultSetToCloseOnStmtToKeep.close();

  closedConn = connToClose;
  openConn = connToKeep;
  closedPlainStmtOfOpenConn = plainStmtToClose;
  closedPreparedStmtOfOpenConn = preparedStmtToClose;
  closedResultSetOfClosedStmt = resultSetToCloseOnStmtToClose;
  closedResultSetOfOpenStmt = resultSetToCloseOnStmtToKeep;
  resultSetMetaDataOfClosedResultSet = rsmdForOpenStmt;
  resultSetMetaDataOfClosedStmt = rsmdForClosedStmt;
  databaseMetaDataOfClosedConn = dbmd;

  // Self-check that member variables are set (and objects are in right open
  // or closed state):
  assertTrue("Test setup error", closedConn.isClosed());
  assertFalse("Test setup error", openConn.isClosed());
  assertTrue("Test setup error", closedPlainStmtOfOpenConn.isClosed());
  assertTrue("Test setup error", closedPreparedStmtOfOpenConn.isClosed());
  assertTrue("Test setup error", closedResultSetOfClosedStmt.isClosed());
  assertTrue("Test setup error", closedResultSetOfOpenStmt.isClosed());
  // (No ResultSetMetaData.isClosed() or DatabaseMetaData.isClosed():)
  assertNotNull("Test setup error", resultSetMetaDataOfClosedResultSet);
  assertNotNull("Test setup error", resultSetMetaDataOfClosedStmt);
  assertNotNull("Test setup error", databaseMetaDataOfClosedConn);
}
 
Example 20
Project: ProyectoPacientes   File: ResultSetRegressionTest.java   Source Code and License Vote up 3 votes
/**
 * Tests fix for BUG#16841 - updatable result set doesn't return
 * AUTO_INCREMENT values for insertRow() when multiple column primary keys
 * are used.
 * 
 * @throws Exception
 *             if the test fails.
 */
public void testBug16841() throws Exception {

    createTable("testBug16841", "(CID int( 20 ) NOT NULL default '0', OID int( 20 ) NOT NULL AUTO_INCREMENT ,"
            + "PatientID int( 20 ) default NULL , PRIMARY KEY ( CID , OID ) , KEY OID ( OID ) , KEY Path ( CID, PatientID))", "MYISAM");

    String sSQLQuery = "SELECT * FROM testBug16841 WHERE 1 = 0";
    Statement updStmt = null;

    try {
        updStmt = this.conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE);

        this.rs = updStmt.executeQuery(sSQLQuery);

        this.rs.moveToInsertRow();

        this.rs.updateInt("CID", 1);
        this.rs.updateInt("PatientID", 1);

        this.rs.insertRow();

        this.rs.last();
        assertEquals(1, this.rs.getInt("OID"));
    } finally {

        if (updStmt != null) {
            updStmt.close();
        }

    }
}