java.sql.PreparedStatement

Here are the examples of the java api class java.sql.PreparedStatement taken from open source projects.

1. TestPreparedStatement#testDataTypes()

View license
private void testDataTypes(Connection conn) throws SQLException {
    conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
    conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
    Statement stat = conn.createStatement();
    PreparedStatement prep;
    ResultSet rs;
    trace("Create tables");
    stat.execute("CREATE TABLE T_INT" + "(ID INT PRIMARY KEY,VALUE INT)");
    stat.execute("CREATE TABLE T_VARCHAR" + "(ID INT PRIMARY KEY,VALUE VARCHAR(255))");
    stat.execute("CREATE TABLE T_DECIMAL_0" + "(ID INT PRIMARY KEY,VALUE DECIMAL(30,0))");
    stat.execute("CREATE TABLE T_DECIMAL_10" + "(ID INT PRIMARY KEY,VALUE DECIMAL(20,10))");
    stat.execute("CREATE TABLE T_DATETIME" + "(ID INT PRIMARY KEY,VALUE DATETIME)");
    prep = conn.prepareStatement("INSERT INTO T_INT VALUES(?,?)", ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
    prep.setInt(1, 1);
    prep.setInt(2, 0);
    prep.executeUpdate();
    prep.setInt(1, 2);
    prep.setInt(2, -1);
    prep.executeUpdate();
    prep.setInt(1, 3);
    prep.setInt(2, 3);
    prep.executeUpdate();
    prep.setInt(1, 4);
    prep.setNull(2, Types.INTEGER, "INTEGER");
    prep.setNull(2, Types.INTEGER);
    prep.executeUpdate();
    prep.setInt(1, 5);
    prep.setBigDecimal(2, new java.math.BigDecimal("0"));
    prep.executeUpdate();
    prep.setInt(1, 6);
    prep.setString(2, "-1");
    prep.executeUpdate();
    prep.setInt(1, 7);
    prep.setObject(2, new Integer(3));
    prep.executeUpdate();
    prep.setObject(1, "8");
    // should throw an exception
    prep.setObject(2, null);
    // some databases don't allow calling setObject with null (no data type)
    prep.executeUpdate();
    prep.setInt(1, 9);
    prep.setObject(2, -4, Types.VARCHAR);
    prep.executeUpdate();
    prep.setInt(1, 10);
    prep.setObject(2, "5", Types.INTEGER);
    prep.executeUpdate();
    prep.setInt(1, 11);
    prep.setObject(2, null, Types.INTEGER);
    prep.executeUpdate();
    prep.setInt(1, 12);
    prep.setBoolean(2, true);
    prep.executeUpdate();
    prep.setInt(1, 13);
    prep.setBoolean(2, false);
    prep.executeUpdate();
    prep.setInt(1, 14);
    prep.setByte(2, (byte) -20);
    prep.executeUpdate();
    prep.setInt(1, 15);
    prep.setByte(2, (byte) 100);
    prep.executeUpdate();
    prep.setInt(1, 16);
    prep.setShort(2, (short) 30000);
    prep.executeUpdate();
    prep.setInt(1, 17);
    prep.setShort(2, (short) (-30000));
    prep.executeUpdate();
    prep.setInt(1, 18);
    prep.setLong(2, Integer.MAX_VALUE);
    prep.executeUpdate();
    prep.setInt(1, 19);
    prep.setLong(2, Integer.MIN_VALUE);
    prep.executeUpdate();
    assertTrue(stat.execute("SELECT * FROM T_INT ORDER BY ID"));
    rs = stat.getResultSet();
    assertResultSetOrdered(rs, new String[][] { { "1", "0" }, { "2", "-1" }, { "3", "3" }, { "4", null }, { "5", "0" }, { "6", "-1" }, { "7", "3" }, { "8", null }, { "9", "-4" }, { "10", "5" }, { "11", null }, { "12", "1" }, { "13", "0" }, { "14", "-20" }, { "15", "100" }, { "16", "30000" }, { "17", "-30000" }, { "18", "" + Integer.MAX_VALUE }, { "19", "" + Integer.MIN_VALUE } });
    prep = conn.prepareStatement("INSERT INTO T_DECIMAL_0 VALUES(?,?)");
    prep.setInt(1, 1);
    prep.setLong(2, Long.MAX_VALUE);
    prep.executeUpdate();
    prep.setInt(1, 2);
    prep.setLong(2, Long.MIN_VALUE);
    prep.executeUpdate();
    prep.setInt(1, 3);
    prep.setFloat(2, 10);
    prep.executeUpdate();
    prep.setInt(1, 4);
    prep.setFloat(2, -20);
    prep.executeUpdate();
    prep.setInt(1, 5);
    prep.setFloat(2, 30);
    prep.executeUpdate();
    prep.setInt(1, 6);
    prep.setFloat(2, -40);
    prep.executeUpdate();
    rs = stat.executeQuery("SELECT VALUE FROM T_DECIMAL_0 ORDER BY ID");
    checkBigDecimal(rs, new String[] { "" + Long.MAX_VALUE, "" + Long.MIN_VALUE, "10", "-20", "30", "-40" });
}

2. BlobClob4BlobTest#insertDefaultData()

Project: derby
Source File: BlobClob4BlobTest.java
View license
private void insertDefaultData() throws Exception {
    PreparedStatement ps = prepareStatement("INSERT INTO testClob (a, b, c) VALUES (?, ?, ?)");
    String clobValue = "";
    ps.setString(1, clobValue);
    ps.setInt(2, clobValue.length());
    ps.setLong(3, 0);
    ps.addBatch();
    clobValue = "you can lead a horse to water but you can't form it " + "into beverage";
    ps.setString(1, clobValue);
    ps.setInt(2, clobValue.length());
    ps.setLong(3, 0);
    ps.addBatch();
    clobValue = "a stitch in time says ouch";
    ps.setString(1, clobValue);
    ps.setInt(2, clobValue.length());
    ps.setLong(3, 0);
    ps.addBatch();
    clobValue = "here is a string with a return \n character";
    ps.setString(1, clobValue);
    ps.setInt(2, clobValue.length());
    ps.setLong(3, 0);
    ps.addBatch();
    ps.executeBatch();
    ps.clearBatch();
    insertLoopingAlphabetStreamData(ps, CharAlphabet.modernLatinLowercase(), 0);
    insertLoopingAlphabetStreamData(ps, CharAlphabet.modernLatinLowercase(), 56);
    insertLoopingAlphabetStreamData(ps, CharAlphabet.modernLatinLowercase(), 5000);
    insertLoopingAlphabetStreamData(ps, CharAlphabet.modernLatinLowercase(), 10000);
    insertLoopingAlphabetStreamData(ps, CharAlphabet.modernLatinLowercase(), 300000);
    ps.setNull(1, Types.CLOB);
    ps.setInt(2, 0);
    ps.setLong(3, 0);
    ps.executeUpdate();
    ps.close();
    ps = prepareStatement("INSERT INTO testBlob (a, b, crc32) VALUES (?, ?, ?)");
    byte[] blobValue = "".getBytes("US-ASCII");
    ps.setBytes(1, blobValue);
    ps.setInt(2, blobValue.length);
    ps.setLong(3, getStreamCheckSum(new ByteArrayInputStream(blobValue)));
    ps.addBatch();
    blobValue = ("you can lead a horse to water but you can't form it " + "into beverage").getBytes("US-ASCII");
    ps.setBytes(1, blobValue);
    ps.setInt(2, blobValue.length);
    ps.setLong(3, getStreamCheckSum(new ByteArrayInputStream(blobValue)));
    ps.addBatch();
    blobValue = "a stitch in time says ouch".getBytes("US-ASCII");
    ps.setBytes(1, blobValue);
    ps.setInt(2, blobValue.length);
    ps.setLong(3, getStreamCheckSum(new ByteArrayInputStream(blobValue)));
    ps.addBatch();
    blobValue = "here is a string with a return \n character".getBytes("US-ASCII");
    ps.setBytes(1, blobValue);
    ps.setInt(2, blobValue.length);
    ps.setLong(3, getStreamCheckSum(new ByteArrayInputStream(blobValue)));
    ps.addBatch();
    ps.executeBatch();
    ps.clearBatch();
    insertLoopingAlphabetStreamData(ps, 0);
    insertLoopingAlphabetStreamData(ps, 56);
    insertLoopingAlphabetStreamData(ps, 5000);
    insertLoopingAlphabetStreamData(ps, 10000);
    insertLoopingAlphabetStreamData(ps, 300000);
    ps.setNull(1, Types.BLOB);
    ps.setInt(2, 0);
    ps.setNull(3, Types.BIGINT);
    ps.executeUpdate();
    ps.close();
    commit();
}

3. maxMemPerTab#createTablesAndInsertData()

Project: derby
Source File: maxMemPerTab.java
View license
private static void createTablesAndInsertData(Connection conn) throws SQLException {
    System.out.println("Start creating tables and inserting data ...");
    //create tables
    PreparedStatement ps = conn.prepareStatement("create table tab1 (c1 int, c2 varchar(20000))");
    ps.execute();
    ps = conn.prepareStatement("create table tab2 (c1 int, c2 varchar(20000))");
    ps.execute();
    ps = conn.prepareStatement("create table tab3 (c1 int, c2 varchar(2000))");
    ps.execute();
    ps = conn.prepareStatement("create table tab4 (c1 int, c2 varchar(2000))");
    ps.execute();
    //insert data
    String largeStringA20000 = new String(Formatters.repeatChar("a", 20000));
    String largeStringA2000 = new String(Formatters.repeatChar("a", 2000));
    String largeStringB20000 = new String(Formatters.repeatChar("b", 20000));
    String largeStringB2000 = new String(Formatters.repeatChar("b", 2000));
    String largeStringC20000 = new String(Formatters.repeatChar("c", 20000));
    String largeStringC2000 = new String(Formatters.repeatChar("c", 2000));
    String largeStringD20000 = new String(Formatters.repeatChar("d", 20000));
    String largeStringD2000 = new String(Formatters.repeatChar("d", 2000));
    ps = conn.prepareStatement("insert into tab1 values (?, ?)");
    ps.setInt(1, 1);
    ps.setString(2, largeStringA20000);
    ps.executeUpdate();
    ps.setInt(1, 2);
    ps.setString(2, largeStringB20000);
    ps.executeUpdate();
    ps.setInt(1, 3);
    ps.setString(2, largeStringC20000);
    ps.executeUpdate();
    ps.close();
    ps = conn.prepareStatement("insert into tab2 values (?, ?)");
    ps.setInt(1, 1);
    ps.setString(2, largeStringA20000);
    ps.executeUpdate();
    ps.setInt(1, 2);
    ps.setString(2, largeStringC20000);
    ps.executeUpdate();
    ps.setInt(1, 3);
    ps.setString(2, largeStringD20000);
    ps.executeUpdate();
    ps.close();
    ps = conn.prepareStatement("insert into tab3 values (?, ?)");
    ps.setInt(1, 1);
    ps.setString(2, largeStringA2000);
    ps.executeUpdate();
    ps.setInt(1, 2);
    ps.setString(2, largeStringB2000);
    ps.executeUpdate();
    ps.setInt(1, 3);
    ps.setString(2, largeStringC2000);
    ps.executeUpdate();
    ps.close();
    ps = conn.prepareStatement("insert into tab4 values (?, ?)");
    ps.setInt(1, 1);
    ps.setString(2, largeStringA2000);
    ps.executeUpdate();
    ps.setInt(1, 2);
    ps.setString(2, largeStringC2000);
    ps.executeUpdate();
    ps.setInt(1, 3);
    ps.setString(2, largeStringD2000);
    ps.executeUpdate();
    ps.close();
    System.out.println("... done creating tables and inserting data.");
}

4. PrepareStatementTest#testParameterTypes()

Project: derby
Source File: PrepareStatementTest.java
View license
/**
     * Tests different data types for input parameters of a PreparedStatement.
     */
public void testParameterTypes() throws Exception {
    PreparedStatement pSt = prepareStatement("create table t2(si smallint,i int, bi bigint, r real, f float, " + "d double precision, n5_2 numeric(5,2), dec10_3 decimal(10,3), " + "ch20 char(20),vc varchar(20), lvc long varchar, " + "b20 char(23) for bit data, vb varchar(23) for bit data, " + "lvb long varchar for bit data,  dt date, tm time, " + "ts timestamp not null)");
    assertUpdateCount(pSt, 0);
    pSt.close();
    // byte array for binary values.
    byte[] ba = new byte[] { 0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf, 0x10, 0x11, 0x12, 0x13 };
    // For padded byte data
    byte[] bapad = new byte[23];
    System.arraycopy(ba, 0, bapad, 0, ba.length);
    // Pad with space!!!
    Arrays.fill(bapad, ba.length, bapad.length, (byte) 0x20);
    // Values to be inserted
    Object[][] t2_rows = { { 1, 2, 3L, 4.0F, 5.0, 6.0, new BigDecimal("77.77"), new BigDecimal("8.100"), "column9string       ", "column10vcstring", "column11lvcstring", bapad, ba, ba, Date.valueOf("2002-04-12"), Time.valueOf("11:44:30"), Timestamp.valueOf("2002-04-12 11:44:30.000000000") }, { 1, 2, 3L, 4.0F, 5.0, 6.0, new BigDecimal("77.77"), new BigDecimal("8.100"), "column11string      ", "column10vcstring", "column11lvcstring", bapad, ba, ba, Date.valueOf("2002-04-12"), Time.valueOf("11:44:30"), Timestamp.valueOf("2002-04-12 11:44:30.000000000") }, { null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, Timestamp.valueOf("2002-04-12 11:44:31.000000000") } };
    pSt = prepareStatement("insert into t2 values (?, ?, ?, ?,  ?, ?, ?, ?, ?, ?, ?, ?, ?, " + "?, ? ,? , ?)");
    pSt.setShort(1, ((Integer) t2_rows[0][0]).shortValue());
    pSt.setInt(2, ((Integer) t2_rows[0][1]).intValue());
    pSt.setLong(3, ((Long) t2_rows[0][2]).longValue());
    pSt.setFloat(4, ((Float) t2_rows[0][3]).floatValue());
    pSt.setDouble(5, ((Double) t2_rows[0][4]).doubleValue());
    pSt.setDouble(6, ((Double) t2_rows[0][5]).doubleValue());
    pSt.setBigDecimal(7, (BigDecimal) t2_rows[0][6]);
    // Diff. precision
    pSt.setBigDecimal(8, new BigDecimal("8.1"));
    // Without padding
    pSt.setString(9, "column9string");
    byte[] c10ba = ((String) t2_rows[0][9]).getBytes("UTF-8");
    int len = c10ba.length;
    pSt.setAsciiStream(10, new ByteArrayInputStream(c10ba), len);
    byte[] c11ba = ((String) t2_rows[0][10]).getBytes("UTF-8");
    len = c11ba.length;
    pSt.setCharacterStream(11, new InputStreamReader(new ByteArrayInputStream(c11ba), "UTF-8"), len);
    pSt.setBytes(12, ba);
    pSt.setBinaryStream(13, new ByteArrayInputStream(ba), ba.length);
    pSt.setBytes(14, ba);
    pSt.setDate(15, ((Date) t2_rows[0][14]));
    pSt.setTime(16, ((Time) t2_rows[0][15]));
    pSt.setTimestamp(17, ((Timestamp) t2_rows[0][16]));
    assertUpdateCount(pSt, 1);
    // PreparedStatement
    for (int i = 0; i < 17; ++i) {
        pSt.setObject(i + 1, t2_rows[1][i]);
    }
    assertUpdateCount(pSt, 1);
    // test setNull on different datatypes of the input parameters of
    // PreparedStatement
    pSt.setNull(1, java.sql.Types.SMALLINT);
    pSt.setNull(2, java.sql.Types.INTEGER);
    pSt.setNull(3, java.sql.Types.BIGINT);
    pSt.setNull(4, java.sql.Types.REAL);
    pSt.setNull(5, java.sql.Types.FLOAT);
    pSt.setNull(6, java.sql.Types.DOUBLE);
    pSt.setNull(7, java.sql.Types.NUMERIC);
    pSt.setNull(8, java.sql.Types.DECIMAL);
    pSt.setNull(9, java.sql.Types.CHAR);
    pSt.setNull(10, java.sql.Types.VARCHAR);
    pSt.setNull(11, java.sql.Types.LONGVARCHAR);
    pSt.setNull(12, java.sql.Types.BINARY);
    pSt.setNull(13, java.sql.Types.VARBINARY);
    pSt.setNull(14, java.sql.Types.LONGVARBINARY);
    pSt.setNull(15, java.sql.Types.DATE);
    pSt.setNull(16, java.sql.Types.TIME);
    pSt.setTimestamp(17, ((Timestamp) t2_rows[2][16]));
    assertFalse(pSt.execute());
    assertEquals(1, pSt.getUpdateCount());
    pSt.close();
    pSt = prepareStatement("select * from t2");
    ResultSet rs = pSt.executeQuery();
    JDBC.assertFullResultSet(rs, t2_rows, false);
    rs.close();
    pSt.close();
    // negative test cases with no parameters set
    try {
        pSt = prepareStatement("select * from t2 where i = ?");
        rs = pSt.executeQuery();
        fail("Exception expected above!");
    } catch (SQLException e) {
        assertSQLState("07000", e);
    }
    rs.close();
    pSt.close();
    try {
        pSt = prepareStatement("insert into t2 values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, " + "?, ?, ?, ?, ?)");
        pSt.executeUpdate();
        fail("Exception expected above!");
    } catch (SQLException e) {
        assertSQLState("07000", e);
    }
    pSt.close();
    // Some test cases for DERBY-2558, involving validation of the
    // parameterIndex argument to the 4-argument overload of setObject
    //
    pSt = prepareStatement("create table d2558 (i int)");
    assertUpdateCount(pSt, 0);
    pSt.close();
    pSt = prepareStatement("insert into d2558 values (3), (4)");
    assertUpdateCount(pSt, 2);
    pSt.close();
    pSt = prepareStatement("select * from d2558 where i = ?");
    pSt.setObject(1, 3, java.sql.Types.INTEGER, 0);
    try {
        // There's only 1 parameter marker, so this should fail:
        pSt.setObject(2, 4, java.sql.Types.INTEGER, 0);
        rs = pSt.executeQuery();
        rs.close();
        fail("Exception expected above!");
    } catch (SQLException e) {
        assertSQLState("XCL13", e);
    }
    pSt.close();
}

5. ParameterMappingTest#testDerby2073()

Project: derby
Source File: ParameterMappingTest.java
View license
/**
     * Test setBigDecimal does not lose fractional digits
     * @throws Exception
     */
public void testDerby2073() throws Exception {
    // Cannot use setBigDecimal with J2ME
    if (!JDBC.vmSupportsJDBC3())
        return;
    Statement s = createStatement();
    s.executeUpdate("CREATE TABLE DERBY_2073_TAB (dc DECIMAL(10,2), db double, r real, i int)");
    PreparedStatement ps = prepareStatement("INSERT INTO DERBY_2073_TAB VALUES(?,?,?,?)");
    BigDecimal value = new BigDecimal("123.45");
    ps.setBigDecimal(1, value);
    ps.setBigDecimal(2, value);
    ps.setBigDecimal(3, value);
    ps.setBigDecimal(4, value);
    ps.executeUpdate();
    // Test with null values as the change sets precision/scale for null values differently
    ps.setBigDecimal(1, null);
    ps.setBigDecimal(2, null);
    ps.setBigDecimal(3, null);
    ps.setBigDecimal(4, null);
    ps.executeUpdate();
    // Can't use negative scale on jdk1.4.2
    if (JDBC.vmSupportsJDBC4()) {
        // Test with negative scale.
        value = new BigDecimal(new BigInteger("2"), -3);
    } else {
        value = new BigDecimal("2000");
    }
    ps.setBigDecimal(1, value);
    ps.setBigDecimal(2, value);
    ps.setBigDecimal(3, value);
    ps.setBigDecimal(4, value);
    ps.executeUpdate();
    value = new BigDecimal("123.45");
    // Test with setObject and scale of 2
    ps.setObject(1, value, java.sql.Types.DECIMAL, 2);
    ps.setObject(2, value, java.sql.Types.DECIMAL, 2);
    ps.setObject(3, value, java.sql.Types.DECIMAL, 2);
    ps.setObject(4, value, java.sql.Types.DECIMAL, 2);
    ps.executeUpdate();
    // Test with setObject and scale of 0
    ps.setObject(1, value, java.sql.Types.DECIMAL, 0);
    ps.setObject(2, value, java.sql.Types.DECIMAL, 0);
    ps.setObject(3, value, java.sql.Types.DECIMAL, 0);
    ps.setObject(4, value, java.sql.Types.DECIMAL, 0);
    ps.executeUpdate();
    // Test with setObject and type with no scale.
    // should default to scale 0
    ps.setObject(1, value, java.sql.Types.DECIMAL);
    ps.setObject(2, value, java.sql.Types.DECIMAL);
    ps.setObject(3, value, java.sql.Types.DECIMAL);
    ps.setObject(4, value, java.sql.Types.DECIMAL);
    ps.executeUpdate();
    // Test with setObject and no type and no scale.
    // Keeps the fractional digits.
    ps.setObject(1, value);
    ps.setObject(2, value);
    ps.setObject(3, value);
    ps.setObject(4, value);
    ps.executeUpdate();
    // Can't use negative scale on jdk1.4.2
    if (JDBC.vmSupportsJDBC4()) {
        // Test with setObject and negative scale.
        value = new BigDecimal(new BigInteger("2"), -3);
    } else {
        value = new BigDecimal("2000");
    }
    ps.setObject(1, value);
    ps.setObject(2, value);
    ps.setObject(3, value);
    ps.setObject(4, value);
    ps.executeUpdate();
    ResultSet rs = s.executeQuery("SELECT * FROM DERBY_2073_TAB");
    String[][] expectedResults = new String[][] { { "123.45", "123.45", "123.45", "123" }, { null, null, null, null }, { "2000.00", "2000.0", "2000.0", "2000" }, { "123.45", "123.45", "123.45", "123" }, { "123.00", "123.0", "123.0", "123" }, { "123.00", "123.0", "123.0", "123" }, { "123.45", "123.45", "123.45", "123" }, { "2000.00", "2000.0", "2000.0", "2000" } };
    // not BigDecimal (e.g. double or real or varchar.) (DERBY-3128)
    if (usingDerbyNetClient())
        JDBC.assertFullResultSet(rs, expectedResults);
    s.executeUpdate("DROP TABLE DERBY_2073_TAB");
}

6. Standard#paymentById()

Project: derby
Source File: Standard.java
View license
private void paymentById(Display display, Object displayData, short w, short d, short cw, short cd, int c, final String amount) throws Exception {
    PreparedStatement pyCustomerPayment = prepareStatement("UPDATE CUSTOMER SET C_BALANCE = C_BALANCE - ?, " + "C_YTD_PAYMENT = C_YTD_PAYMENT + ?, " + "C_PAYMENT_CNT = C_PAYMENT_CNT + 1 " + "WHERE C_W_ID = ? AND C_D_ID = ? AND C_ID = ?");
    PreparedStatement pyCustomerInfoId = prepareStatement("SELECT C_FIRST, C_MIDDLE, C_LAST, C_BALANCE, " + "C_STREET_1, C_STREET_2, C_CITY, C_STATE, C_ZIP, " + "C_PHONE, C_SINCE, C_CREDIT, C_CREDIT_LIM, C_DISCOUNT " + "FROM CUSTOMER WHERE C_W_ID = ? AND C_D_ID = ? AND C_ID = ?");
    PreparedStatement pyCustomerUpdateBadCredit = prepareStatement("UPDATE CUSTOMER SET C_DATA = " + " BAD_CREDIT_DATA(C_DATA, ?, ?, C_W_ID, C_W_ID, C_ID, ?) " + "WHERE C_W_ID = ? AND C_D_ID = ? AND C_ID = ?");
    PreparedStatement pyCustomerGetData = prepareStatement("SELECT SUBSTR(C_DATA, 1, 200) AS C_DATA_200 " + "FROM CUSTOMER WHERE C_W_ID = ? AND C_D_ID = ? AND C_ID = ?");
    PreparedStatement pyDistrictUpdate = prepareStatement("UPDATE DISTRICT SET D_YTD = D_YTD + ? WHERE D_W_ID = ? AND D_ID = ?");
    PreparedStatement pyDistrictInfo = prepareStatement("SELECT D_NAME, D_STREET_1, D_STREET_2, D_CITY, D_STATE, D_ZIP FROM DISTRICT WHERE D_W_ID = ? AND D_ID = ? ");
    PreparedStatement pyWarehouseUpdate = prepareStatement("UPDATE WAREHOUSE SET W_YTD = W_YTD + ? WHERE W_ID = ?");
    PreparedStatement pyWarehouseInfo = prepareStatement("SELECT W_NAME, W_STREET_1, W_STREET_2, W_CITY, W_STATE, W_ZIP " + "FROM WAREHOUSE WHERE W_ID = ?");
    PreparedStatement pyHistory = prepareStatement("INSERT INTO HISTORY(H_C_ID, H_C_D_ID, H_C_W_ID, H_D_ID, H_W_ID, " + "H_DATE, H_AMOUNT, H_DATA) " + "VALUES (?, ?, ?, ?, ?, CURRENT TIMESTAMP, ?, ?)");
    Customer customer = new Customer();
    customer.setWarehouse(cw);
    customer.setDistrict(cd);
    customer.setId(c);
    // Update the customer assuming that they have good credit
    pyCustomerPayment.setString(1, amount);
    pyCustomerPayment.setString(2, amount);
    pyCustomerPayment.setShort(3, cw);
    pyCustomerPayment.setShort(4, cd);
    pyCustomerPayment.setInt(5, c);
    pyCustomerPayment.executeUpdate();
    // Get the customer information
    pyCustomerInfoId.setShort(1, cw);
    pyCustomerInfoId.setShort(2, cd);
    pyCustomerInfoId.setInt(3, c);
    ResultSet rs = pyCustomerInfoId.executeQuery();
    rs.next();
    customer.setFirst(rs.getString("C_FIRST"));
    customer.setMiddle(rs.getString("C_MIDDLE"));
    customer.setLast(rs.getString("C_LAST"));
    customer.setBalance(rs.getString("C_BALANCE"));
    customer.setAddress(getAddress(rs, "C_STREET_1"));
    customer.setPhone(rs.getString("C_PHONE"));
    customer.setSince(rs.getTimestamp("C_SINCE"));
    customer.setCredit(rs.getString("C_CREDIT"));
    customer.setCredit_lim(rs.getString("C_CREDIT_LIM"));
    customer.setDiscount(rs.getString("C_DISCOUNT"));
    reset(pyCustomerInfoId);
    // additional work for bad credit customers.
    if ("BC".equals(customer.getCredit())) {
        pyCustomerUpdateBadCredit.setShort(1, w);
        pyCustomerUpdateBadCredit.setShort(2, d);
        pyCustomerUpdateBadCredit.setString(3, amount);
        pyCustomerUpdateBadCredit.setShort(4, cw);
        pyCustomerUpdateBadCredit.setShort(5, cd);
        pyCustomerUpdateBadCredit.setInt(6, c);
        pyCustomerUpdateBadCredit.executeUpdate();
        reset(pyCustomerUpdateBadCredit);
        // Need to display the first 200 characters
        // of C_DATA information if the customer has
        // bad credit.
        pyCustomerGetData.setShort(1, cw);
        pyCustomerGetData.setShort(2, cd);
        pyCustomerGetData.setInt(3, c);
        rs = pyCustomerGetData.executeQuery();
        rs.next();
        customer.setData(rs.getString("C_DATA_200"));
        reset(pyCustomerGetData);
    }
    district.clear();
    district.setWarehouse(w);
    district.setId(d);
    // Update DISTRICT
    pyDistrictUpdate.setString(1, amount);
    pyDistrictUpdate.setShort(2, w);
    pyDistrictUpdate.setShort(3, d);
    pyDistrictUpdate.executeUpdate();
    reset(pyDistrictUpdate);
    // Get the required information from DISTRICT
    pyDistrictInfo.setShort(1, w);
    pyDistrictInfo.setShort(2, d);
    rs = pyDistrictInfo.executeQuery();
    rs.next();
    district.setName(rs.getString("D_NAME"));
    district.setAddress(getAddress(rs, "D_STREET_1"));
    reset(pyDistrictInfo);
    warehouse.clear();
    warehouse.setId(w);
    // Update WAREHOUSE
    pyWarehouseUpdate.setString(1, amount);
    pyWarehouseUpdate.setShort(2, w);
    pyWarehouseUpdate.executeUpdate();
    reset(pyWarehouseUpdate);
    // Get the required information from WAREHOUSE
    pyWarehouseInfo.setShort(1, w);
    rs = pyWarehouseInfo.executeQuery();
    rs.next();
    warehouse.setName(rs.getString("W_NAME"));
    warehouse.setAddress(getAddress(rs, "W_STREET_1"));
    reset(pyWarehouseInfo);
    // Insert HISTORY row
    pyHistory.setInt(1, c);
    pyHistory.setShort(2, cd);
    pyHistory.setShort(3, cw);
    pyHistory.setShort(4, d);
    pyHistory.setShort(5, w);
    pyHistory.setString(6, amount);
    StringBuffer hData = new StringBuffer(24);
    hData.append(warehouse.getName());
    hData.append("    ");
    hData.append(district.getName());
    pyHistory.setString(7, hData.toString());
    pyHistory.executeUpdate();
    reset(pyHistory);
    conn.commit();
}

7. DeclareGlobalTempTableJavaJDBC30Test#testSavepointRollbackbehaviour13()

View license
/**
     *  Savepoint and Rollback behavior - 13 - 3Q
     *  tests the rollback , savepoint behaviour with prepartedStatement
     *  
     *  @throws SQLException 
     */
public void testSavepointRollbackbehaviour13() throws SQLException {
    Statement s = createStatement();
    s.executeUpdate("DECLARE GLOBAL TEMPORARY TABLE SESSION.t2(" + "c21 int, c22 int) not logged on commit preserve rows");
    PreparedStatement pStmtInsert = prepareStatement("insert into SESSION.t2 values (?, ?)");
    pStmtInsert.setInt(1, 21);
    pStmtInsert.setInt(2, 1);
    pStmtInsert.execute();
    pStmtInsert.setInt(1, 22);
    pStmtInsert.setInt(2, 2);
    pStmtInsert.execute();
    pStmtInsert.setInt(1, 23);
    pStmtInsert.setInt(2, 2);
    pStmtInsert.execute();
    PreparedStatement pStmtUpdate = prepareStatement("UPDATE SESSION.t2 SET c22 = 3 where c21=?");
    pStmtUpdate.setInt(1, 23);
    pStmtUpdate.execute();
    PreparedStatement pStmtDelete = prepareStatement("DELETE FROM SESSION.t2 where c21 = ?");
    pStmtDelete.setInt(1, 23);
    pStmtDelete.execute();
    //committing point
    commit();
    JDBC.assertSingleValueResultSet(s.executeQuery("select count(*) from SESSION.t2"), "2");
    //set the first savepoint
    Savepoint savepoint1 = getConnection().setSavepoint();
    pStmtInsert.setInt(1, 23);
    pStmtInsert.setInt(2, 2);
    pStmtInsert.execute();
    JDBC.assertSingleValueResultSet(s.executeQuery("select count(*) from SESSION.t2"), "3");
    //set the second savepoint
    Savepoint savepoint2 = getConnection().setSavepoint();
    pStmtUpdate.setInt(1, 23);
    pStmtUpdate.execute();
    JDBC.assertSingleValueResultSet(s.executeQuery("select count(*) from SESSION.t2"), "3");
    //rollback savepoint2 and should loose all the data from t2");
    getConnection().rollback(savepoint2);
    JDBC.assertSingleValueResultSet(s.executeQuery("select count(*) from SESSION.t2"), "0");
    //Create savepoint3, insert some rows into t2 using prepared statement
    Savepoint savepoint3 = getConnection().setSavepoint();
    pStmtInsert.setInt(1, 21);
    pStmtInsert.setInt(2, 1);
    pStmtInsert.execute();
    pStmtInsert.setInt(1, 22);
    pStmtInsert.setInt(2, 2);
    pStmtInsert.execute();
    pStmtInsert.setInt(1, 23);
    pStmtInsert.setInt(2, 333);
    pStmtInsert.execute();
    JDBC.assertSingleValueResultSet(s.executeQuery("select count(*) from SESSION.t2"), "3");
    //Create savepoint4 and update row inserted in savepoint3 using prepared
    //statement and inspect the data in t2
    Savepoint savepoint4 = getConnection().setSavepoint();
    pStmtUpdate.setInt(1, 23);
    pStmtUpdate.execute();
    JDBC.assertSingleValueResultSet(s.executeQuery("select count(*) from SESSION.t2"), "3");
    //release savepoint4
    getConnection().releaseSavepoint(savepoint4);
    JDBC.assertSingleValueResultSet(s.executeQuery("select count(*) from SESSION.t2"), "3");
    pStmtDelete.setInt(1, 23);
    pStmtDelete.execute();
    //Commit transaction and should see data in t2
    commit();
    JDBC.assertSingleValueResultSet(s.executeQuery("select count(*) from SESSION.t2"), "2");
    s.executeUpdate("drop table SESSION.t2");
}

8. ArrayTest#testSetNull()

Project: pgjdbc
Source File: ArrayTest.java
View license
@Test
public void testSetNull() throws SQLException {
    PreparedStatement pstmt = conn.prepareStatement("INSERT INTO arrtest VALUES (?,?,?)");
    pstmt.setNull(1, Types.ARRAY);
    pstmt.setNull(2, Types.ARRAY);
    pstmt.setNull(3, Types.ARRAY);
    pstmt.executeUpdate();
    pstmt.setObject(1, null, Types.ARRAY);
    pstmt.setObject(2, null);
    pstmt.setObject(3, null);
    pstmt.executeUpdate();
    pstmt.setArray(1, null);
    pstmt.setArray(2, null);
    pstmt.setArray(3, null);
    pstmt.executeUpdate();
    pstmt.close();
}

9. ArrayTest#testSetNull()

Project: pgjdbc-ng
Source File: ArrayTest.java
View license
@Test
public void testSetNull() throws SQLException {
    PreparedStatement pstmt = conn.prepareStatement("INSERT INTO arrtest VALUES (?,?,?)");
    pstmt.setNull(1, Types.ARRAY);
    pstmt.setNull(2, Types.ARRAY);
    pstmt.setNull(3, Types.ARRAY);
    pstmt.executeUpdate();
    pstmt.setObject(1, null, Types.ARRAY);
    pstmt.setObject(2, null);
    pstmt.setObject(3, null);
    pstmt.executeUpdate();
    pstmt.setArray(1, null);
    pstmt.setArray(2, null);
    pstmt.setArray(3, null);
    pstmt.executeUpdate();
    pstmt.close();
}

10. BlobTest#testSetNull()

Project: pgjdbc-ng
Source File: BlobTest.java
View license
@Test
public void testSetNull() throws Exception {
    PreparedStatement pstmt = conn.prepareStatement("INSERT INTO testblob(lo) VALUES (?)");
    pstmt.setBlob(1, (Blob) null);
    pstmt.executeUpdate();
    pstmt.setNull(1, Types.BLOB);
    pstmt.executeUpdate();
    pstmt.setObject(1, null, Types.BLOB);
    pstmt.executeUpdate();
    pstmt.setClob(1, (Clob) null);
    pstmt.executeUpdate();
    pstmt.setNull(1, Types.CLOB);
    pstmt.executeUpdate();
    pstmt.setObject(1, null, Types.CLOB);
    pstmt.executeUpdate();
    pstmt.close();
}

11. BooleanValuesTest#minion_4889()

Project: derby
Source File: BooleanValuesTest.java
View license
private void minion_4889(Connection conn, int value, boolean expectedBooleanResult) throws Exception {
    goodStatement(conn, "delete from t_4889");
    PreparedStatement ps = chattyPrepare(conn, "insert into t_4889( key_col, setter_col, boolean_col ) values ( ?, ?, ? )");
    ps.setInt(1, 1);
    ps.setString(2, "setByte");
    ps.setByte(3, (byte) value);
    ps.execute();
    ps.setInt(1, 2);
    ps.setString(2, "setShort");
    ps.setShort(3, (short) value);
    ps.execute();
    ps.setInt(1, 3);
    ps.setString(2, "setInt");
    ps.setInt(3, value);
    ps.execute();
    ps.setInt(1, 4);
    ps.setString(2, "setLong");
    ps.setLong(3, (long) value);
    ps.execute();
    ps.setInt(1, 5);
    ps.setString(2, "setObject( Byte )");
    ps.setObject(3, (byte) value);
    ps.execute();
    ps.setInt(1, 6);
    ps.setString(2, "setObject( Short )");
    ps.setObject(3, (short) value);
    ps.execute();
    ps.setInt(1, 7);
    ps.setString(2, "setObject( Integer )");
    ps.setObject(3, value);
    ps.execute();
    ps.setInt(1, 8);
    ps.setString(2, "setObject( Long )");
    ps.setObject(3, (long) value);
    ps.execute();
    String stringValue = Boolean.toString((value != 0));
    assertResults(conn, "select * from t_4889 order by key_col", new String[][] { { "1", "setByte", stringValue }, { "2", "setShort", stringValue }, { "3", "setInt", stringValue }, { "4", "setLong", stringValue }, { "5", "setObject( Byte )", stringValue }, { "6", "setObject( Short )", stringValue }, { "7", "setObject( Integer )", stringValue }, { "8", "setObject( Long )", stringValue } }, false);
}

12. BlobTest#testSetNull()

Project: pgjdbc
Source File: BlobTest.java
View license
public void testSetNull() throws Exception {
    PreparedStatement pstmt = con.prepareStatement("INSERT INTO testblob(lo) VALUES (?)");
    pstmt.setBlob(1, (Blob) null);
    pstmt.executeUpdate();
    pstmt.setNull(1, Types.BLOB);
    pstmt.executeUpdate();
    pstmt.setObject(1, null, Types.BLOB);
    pstmt.executeUpdate();
    pstmt.setClob(1, (Clob) null);
    pstmt.executeUpdate();
    pstmt.setNull(1, Types.CLOB);
    pstmt.executeUpdate();
    pstmt.setObject(1, null, Types.CLOB);
    pstmt.executeUpdate();
}

13. PrepareStatementTest#testAlternatingLobValuesAndNull()

Project: derby
Source File: PrepareStatementTest.java
View license
/**
     * This test case ensures that the bug introduced by the first patch for
     * Jira-815 has not been re-introduced.  The bug resulted in a hang if a
     * prepared statement was first executed with a lob value, and then
     * re-executed with a null-value in place of the lob.
     */
public void testAlternatingLobValuesAndNull() throws Exception {
    getConnection().setAutoCommit(false);
    Statement st = createStatement();
    st.execute("create table tt1 (CLICOL01 smallint not null)");
    st.execute("alter table tt1 add clicol02 smallint");
    st.execute("alter table tt1 add clicol03 int not null default 1");
    st.execute("alter table tt1 add clicol04 int");
    st.execute("alter table tt1 add clicol05 decimal(10,0) not null default 1");
    st.execute("alter table tt1 add clicol51 blob(1G)");
    st.execute("alter table tt1 add clicol52 blob(50)");
    st.execute("alter table tt1 add clicol53 clob(2G) not null default ''");
    st.execute("alter table tt1 add clicol54 clob(60)");
    commit();
    PreparedStatement pSt = prepareStatement("insert into tt1 values (?,?,?,?,?,?,?,?,?)");
    pSt.setShort(1, (short) 500);
    pSt.setShort(2, (short) 501);
    pSt.setInt(3, 496);
    pSt.setInt(4, 497);
    pSt.setDouble(5, 484);
    pSt.setBytes(6, "404 bit".getBytes());
    pSt.setBytes(7, "405 bit".getBytes());
    pSt.setString(8, "408 bit");
    pSt.setString(9, "409 bit");
    // Inserting first row
    assertUpdateCount(pSt, 1);
    pSt.setNull(2, java.sql.Types.SMALLINT);
    pSt.setNull(4, java.sql.Types.DOUBLE);
    pSt.setNull(7, java.sql.Types.BLOB);
    pSt.setNull(9, java.sql.Types.CLOB);
    // Inserting second row
    assertUpdateCount(pSt, 1);
    // Now inserting 3rd row, using lobs from 1st row
    ResultSet rs = st.executeQuery("select * from tt1");
    rs.next();
    pSt.setShort(1, rs.getShort(1));
    pSt.setShort(2, rs.getShort(2));
    pSt.setInt(3, rs.getInt(3));
    pSt.setInt(4, rs.getInt(4));
    pSt.setDouble(5, rs.getDouble(5));
    pSt.setBlob(6, rs.getBlob(6));
    pSt.setBlob(7, rs.getBlob(7));
    pSt.setClob(8, rs.getClob(8));
    pSt.setClob(9, rs.getClob(9));
    pSt.execute();
    // Now inserting 4th row, using lobs from 2nd row
    rs.next();
    pSt.setNull(2, java.sql.Types.SMALLINT);
    pSt.setNull(4, java.sql.Types.DOUBLE);
    pSt.setBlob(6, rs.getBlob(6));
    pSt.setNull(7, java.sql.Types.BLOB);
    pSt.setClob(8, rs.getClob(8));
    pSt.setNull(9, java.sql.Types.CLOB);
    pSt.execute();
    rs.close();
    pSt.close();
    commit();
}

14. LuceneCoarseAuthorizationTest#createPoemsTable()

View license
public static void createPoemsTable(Connection conn) throws Exception {
    conn.prepareStatement("create table poems\n" + "(\n" + "    poemID int,\n" + "    versionStamp int not null,\n" + "    originalAuthor       varchar( 50 ),\n" + "    lastEditor           varchar( 50 ),\n" + "    poemText            clob,\n" + "    constraint poemsKey primary key( poemID, versionStamp )\n" + ")\n").execute();
    PreparedStatement ps = conn.prepareStatement("insert into poems values ( ?, ?, ?, ?, ? )");
    int poemID = 1;
    int versionStamp = 1;
    ps.setInt(1, poemID++);
    ps.setInt(2, versionStamp++);
    ps.setString(3, "Geoffrey Chaucer");
    ps.setString(4, "Geoffrey Chaucer");
    ps.setString(5, "Whan that Aprill, with his shoures soote The droghte of March hath perced to the roote And bathed every veyne in swich licour, Of which vertu engendred is the flour;");
    ps.executeUpdate();
    ps.setInt(1, poemID++);
    ps.setInt(2, versionStamp++);
    ps.setString(3, "Andrew Marvell");
    ps.setString(4, "Andrew Marvell");
    ps.setString(5, "Had we but world enough, and time, This coyness, lady, were no crime.");
    ps.executeUpdate();
    ps.setInt(1, poemID++);
    ps.setInt(2, versionStamp++);
    ps.setString(3, "John Milton");
    ps.setString(4, "John Milton");
    ps.setString(5, "From morn to noon he fell, from noon to dewy eve, a summers day, and with the setting sun dropped from the ze4ith like a falling star on Lemnos, the Aegean isle");
    ps.executeUpdate();
    ps.setInt(1, poemID++);
    ps.setInt(2, versionStamp++);
    ps.setString(3, "Lord Byron");
    ps.setString(4, "Lord Byron");
    ps.setString(5, "The Assyrian came down like the wolf on the fold, And his cohorts were gleaming in purple and gold; And the sheen of their spears was like stars on the sea, When the blue wave rolls nightly on deep Galilee.");
    ps.executeUpdate();
    ps.setInt(1, poemID++);
    ps.setInt(2, versionStamp++);
    ps.setString(3, "Walt Whitman");
    ps.setString(4, "Walt Whitman");
    ps.setString(5, "When lilacs last in the dooryard bloomd, And the great star early droopd in the western sky in the night, I mournd, and yet shall mourn with ever-returning spring.");
    ps.executeUpdate();
    ps.close();
}

15. LuceneCollationTest#createPoemsTable()

Project: derby
Source File: LuceneCollationTest.java
View license
private void createPoemsTable(Connection conn) throws Exception {
    goodStatement(conn, "create table poems\n" + "(\n" + "    poemID int,\n" + "    versionStamp int not null,\n" + "    originalAuthor       varchar( 50 ),\n" + "    lastEditor           varchar( 50 ),\n" + "    poemText            clob,\n" + "    constraint poemsKey primary key( poemID, versionStamp )\n" + ")\n");
    PreparedStatement ps = conn.prepareStatement("insert into poems values ( ?, ?, ?, ?, ? )");
    int poemID = 1;
    int versionStamp = 1;
    ps.setInt(1, poemID++);
    ps.setInt(2, versionStamp++);
    ps.setString(3, "Geoffrey Chaucer");
    ps.setString(4, "Geoffrey Chaucer");
    ps.setString(5, "Whan that Aprill, with his shoures soote The droghte of March hath perced to the roote And bathed every veyne in swich licour, Of which vertu engendred is the flour;");
    ps.executeUpdate();
    ps.setInt(1, poemID++);
    ps.setInt(2, versionStamp++);
    ps.setString(3, "Andrew Marvell");
    ps.setString(4, "Andrew Marvell");
    ps.setString(5, "Had we but world enough, and time, This coyness, lady, were no crime.");
    ps.executeUpdate();
    ps.setInt(1, poemID++);
    ps.setInt(2, versionStamp++);
    ps.setString(3, "John Milton");
    ps.setString(4, "John Milton");
    ps.setString(5, "From morn to noon he fell, from noon to dewy eve, a summers day, and with the setting sun dropped from the ze4ith like a falling star on Lemnos, the Aegean isle");
    ps.executeUpdate();
    ps.setInt(1, poemID++);
    ps.setInt(2, versionStamp++);
    ps.setString(3, "Lord Byron");
    ps.setString(4, "Lord Byron");
    ps.setString(5, "The Assyrian came down like the wolf on the fold, And his cohorts were gleaming in purple and gold; And the sheen of their spears was like stars on the sea, When the blue wave rolls nightly on deep Galilee.");
    ps.executeUpdate();
    ps.setInt(1, poemID++);
    ps.setInt(2, versionStamp++);
    ps.setString(3, "Walt Whitman");
    ps.setString(4, "Walt Whitman");
    ps.setString(5, "When lilacs last in the dooryard bloomd, And the great star early droopd in the western sky in the night, I mournd, and yet shall mourn with ever-returning spring.");
    ps.executeUpdate();
    ps.close();
}

16. ImportExportBaseTest#doImportData()

Project: derby
Source File: ImportExportBaseTest.java
View license
/**
     *  Perform import using SYSCS_UTIL.SYSCS_IMPORT_DATA procedure.
     */
protected void doImportData(String schemaName, String tableName, String insertCols, String colIndexes, String fileName, String colDel, String charDel, String codeset, int replace) throws SQLException {
    String impsql = "call SYSCS_UTIL.SYSCS_IMPORT_DATA(?, ?, ?, ?, ?, ?, ?, ?, ?)";
    PreparedStatement ps = prepareStatement(impsql);
    ps.setString(1, schemaName);
    ps.setString(2, tableName);
    ps.setString(3, insertCols);
    ps.setString(4, colIndexes);
    ps.setString(5, fileName);
    ps.setString(6, colDel);
    ps.setString(7, charDel);
    ps.setString(8, codeset);
    ps.setInt(9, replace);
    ps.execute();
    ps.close();
}

17. TimestampTest#testSetTimestampWOTZ()

Project: pgjdbc
Source File: TimestampTest.java
View license
/*
   * Tests the timestamp methods in PreparedStatement on timestamp without time zone we insert a
   * value using setTimestamp then see that we get back the same value from getTimestamp (which we
   * know works as it was tested independently of setTimestamp
   */
public void testSetTimestampWOTZ() throws SQLException {
    Statement stmt = con.createStatement();
    PreparedStatement pstmt = con.prepareStatement(TestUtil.insertSQL(TSWOTZ_TABLE, "?"));
    pstmt.setTimestamp(1, TS1WOTZ);
    assertEquals(1, pstmt.executeUpdate());
    pstmt.setTimestamp(1, TS2WOTZ);
    assertEquals(1, pstmt.executeUpdate());
    pstmt.setTimestamp(1, TS3WOTZ);
    assertEquals(1, pstmt.executeUpdate());
    pstmt.setTimestamp(1, TS4WOTZ);
    assertEquals(1, pstmt.executeUpdate());
    pstmt.setTimestamp(1, TS5WOTZ);
    assertEquals(1, pstmt.executeUpdate());
    pstmt.setTimestamp(1, TS6WOTZ);
    assertEquals(1, pstmt.executeUpdate());
    // With java.sql.Timestamp
    pstmt.setObject(1, TS1WOTZ, java.sql.Types.TIMESTAMP);
    assertEquals(1, pstmt.executeUpdate());
    pstmt.setObject(1, TS2WOTZ, java.sql.Types.TIMESTAMP);
    assertEquals(1, pstmt.executeUpdate());
    pstmt.setObject(1, TS3WOTZ, java.sql.Types.TIMESTAMP);
    assertEquals(1, pstmt.executeUpdate());
    pstmt.setObject(1, TS4WOTZ, java.sql.Types.TIMESTAMP);
    assertEquals(1, pstmt.executeUpdate());
    pstmt.setObject(1, TS5WOTZ, java.sql.Types.TIMESTAMP);
    assertEquals(1, pstmt.executeUpdate());
    pstmt.setObject(1, TS6WOTZ, java.sql.Types.TIMESTAMP);
    assertEquals(1, pstmt.executeUpdate());
    // With Strings
    pstmt.setObject(1, TS1WOTZ_PGFORMAT, java.sql.Types.TIMESTAMP);
    assertEquals(1, pstmt.executeUpdate());
    pstmt.setObject(1, TS2WOTZ_PGFORMAT, java.sql.Types.TIMESTAMP);
    assertEquals(1, pstmt.executeUpdate());
    pstmt.setObject(1, TS3WOTZ_PGFORMAT, java.sql.Types.TIMESTAMP);
    assertEquals(1, pstmt.executeUpdate());
    pstmt.setObject(1, TS4WOTZ_PGFORMAT, java.sql.Types.TIMESTAMP);
    assertEquals(1, pstmt.executeUpdate());
    pstmt.setObject(1, TS5WOTZ_PGFORMAT, java.sql.Types.TIMESTAMP);
    assertEquals(1, pstmt.executeUpdate());
    pstmt.setObject(1, TS6WOTZ_PGFORMAT, java.sql.Types.TIMESTAMP);
    assertEquals(1, pstmt.executeUpdate());
    // With java.sql.Date
    pstmt.setObject(1, tmpDate1WOTZ, java.sql.Types.TIMESTAMP);
    assertEquals(1, pstmt.executeUpdate());
    pstmt.setObject(1, tmpDate2WOTZ, java.sql.Types.TIMESTAMP);
    assertEquals(1, pstmt.executeUpdate());
    pstmt.setObject(1, tmpDate3WOTZ, java.sql.Types.TIMESTAMP);
    assertEquals(1, pstmt.executeUpdate());
    pstmt.setObject(1, tmpDate4WOTZ, java.sql.Types.TIMESTAMP);
    assertEquals(1, pstmt.executeUpdate());
    pstmt.setObject(1, tmpDate5WOTZ, java.sql.Types.TIMESTAMP);
    assertEquals(1, pstmt.executeUpdate());
    pstmt.setObject(1, tmpDate6WOTZ, java.sql.Types.TIMESTAMP);
    assertEquals(1, pstmt.executeUpdate());
    // With java.sql.Time
    pstmt.setObject(1, tmpTime1WOTZ, java.sql.Types.TIMESTAMP);
    assertEquals(1, pstmt.executeUpdate());
    pstmt.setObject(1, tmpTime2WOTZ, java.sql.Types.TIMESTAMP);
    assertEquals(1, pstmt.executeUpdate());
    pstmt.setObject(1, tmpTime3WOTZ, java.sql.Types.TIMESTAMP);
    assertEquals(1, pstmt.executeUpdate());
    pstmt.setObject(1, tmpTime4WOTZ, java.sql.Types.TIMESTAMP);
    assertEquals(1, pstmt.executeUpdate());
    pstmt.setObject(1, tmpTime5WOTZ, java.sql.Types.TIMESTAMP);
    assertEquals(1, pstmt.executeUpdate());
    pstmt.setObject(1, tmpTime6WOTZ, java.sql.Types.TIMESTAMP);
    assertEquals(1, pstmt.executeUpdate());
    // Fall through helper
    timestampTestWOTZ();
    assertEquals(30, stmt.executeUpdate("DELETE FROM " + TSWOTZ_TABLE));
    pstmt.close();
    stmt.close();
}

18. PreparedStatementTest#testSetNull()

View license
@Test
public void testSetNull() throws SQLException {
    // valid: fully qualified type to setNull()
    PreparedStatement pstmt = conn.prepareStatement("INSERT INTO texttable (te) VALUES (?)");
    pstmt.setNull(1, Types.VARCHAR);
    pstmt.executeUpdate();
    // valid: fully qualified type to setObject()
    pstmt.setObject(1, null, Types.VARCHAR);
    pstmt.executeUpdate();
    // setObject() with no type info
    pstmt.setObject(1, null);
    pstmt.executeUpdate();
    // setObject() with insufficient type info
    pstmt.setObject(1, null, Types.OTHER);
    pstmt.executeUpdate();
    // setNull() with insufficient type info
    pstmt.setNull(1, Types.OTHER);
    pstmt.executeUpdate();
    pstmt.close();
}

19. TimestampTest#testSetTimestampWOTZ()

Project: pgjdbc-ng
Source File: TimestampTest.java
View license
/*
   * Tests the timestamp methods in PreparedStatement on timestamp without time
   * zone we insert a value using setTimestamp then see that we get back the
   * same value from getTimestamp (which we know works as it was tested
   * independently of setTimestamp
   */
@Test
public void testSetTimestampWOTZ() throws SQLException {
    Statement stmt = con.createStatement();
    PreparedStatement pstmt = con.prepareStatement(TestUtil.insertSQL(TSWOTZ_TABLE, "?"));
    pstmt.setTimestamp(1, TS1WOTZ);
    assertEquals(1, pstmt.executeUpdate());
    pstmt.setTimestamp(1, TS2WOTZ);
    assertEquals(1, pstmt.executeUpdate());
    pstmt.setTimestamp(1, TS3WOTZ);
    assertEquals(1, pstmt.executeUpdate());
    pstmt.setTimestamp(1, TS4WOTZ);
    assertEquals(1, pstmt.executeUpdate());
    pstmt.setTimestamp(1, TS5WOTZ);
    assertEquals(1, pstmt.executeUpdate());
    pstmt.setTimestamp(1, TS6WOTZ);
    assertEquals(1, pstmt.executeUpdate());
    // With java.sql.Timestamp
    pstmt.setObject(1, TS1WOTZ, java.sql.Types.TIMESTAMP);
    assertEquals(1, pstmt.executeUpdate());
    pstmt.setObject(1, TS2WOTZ, java.sql.Types.TIMESTAMP);
    assertEquals(1, pstmt.executeUpdate());
    pstmt.setObject(1, TS3WOTZ, java.sql.Types.TIMESTAMP);
    assertEquals(1, pstmt.executeUpdate());
    pstmt.setObject(1, TS4WOTZ, java.sql.Types.TIMESTAMP);
    assertEquals(1, pstmt.executeUpdate());
    pstmt.setObject(1, TS5WOTZ, java.sql.Types.TIMESTAMP);
    assertEquals(1, pstmt.executeUpdate());
    pstmt.setObject(1, TS6WOTZ, java.sql.Types.TIMESTAMP);
    assertEquals(1, pstmt.executeUpdate());
    // With Strings
    pstmt.setObject(1, TS1WOTZ_PGFORMAT, java.sql.Types.TIMESTAMP);
    assertEquals(1, pstmt.executeUpdate());
    pstmt.setObject(1, TS2WOTZ_PGFORMAT, java.sql.Types.TIMESTAMP);
    assertEquals(1, pstmt.executeUpdate());
    pstmt.setObject(1, TS3WOTZ_PGFORMAT, java.sql.Types.TIMESTAMP);
    assertEquals(1, pstmt.executeUpdate());
    pstmt.setObject(1, TS4WOTZ_PGFORMAT, java.sql.Types.TIMESTAMP);
    assertEquals(1, pstmt.executeUpdate());
    pstmt.setObject(1, TS5WOTZ_PGFORMAT, java.sql.Types.TIMESTAMP);
    assertEquals(1, pstmt.executeUpdate());
    pstmt.setObject(1, TS6WOTZ_PGFORMAT, java.sql.Types.TIMESTAMP);
    assertEquals(1, pstmt.executeUpdate());
    // With java.sql.Date
    pstmt.setObject(1, tmpDate1WOTZ, java.sql.Types.TIMESTAMP);
    assertEquals(1, pstmt.executeUpdate());
    pstmt.setObject(1, tmpDate2WOTZ, java.sql.Types.TIMESTAMP);
    assertEquals(1, pstmt.executeUpdate());
    pstmt.setObject(1, tmpDate3WOTZ, java.sql.Types.TIMESTAMP);
    assertEquals(1, pstmt.executeUpdate());
    pstmt.setObject(1, tmpDate4WOTZ, java.sql.Types.TIMESTAMP);
    assertEquals(1, pstmt.executeUpdate());
    pstmt.setObject(1, tmpDate5WOTZ, java.sql.Types.TIMESTAMP);
    assertEquals(1, pstmt.executeUpdate());
    pstmt.setObject(1, tmpDate6WOTZ, java.sql.Types.TIMESTAMP);
    assertEquals(1, pstmt.executeUpdate());
    // With java.sql.Time
    pstmt.setObject(1, tmpTime1WOTZ, java.sql.Types.TIMESTAMP);
    assertEquals(1, pstmt.executeUpdate());
    pstmt.setObject(1, tmpTime2WOTZ, java.sql.Types.TIMESTAMP);
    assertEquals(1, pstmt.executeUpdate());
    pstmt.setObject(1, tmpTime3WOTZ, java.sql.Types.TIMESTAMP);
    assertEquals(1, pstmt.executeUpdate());
    pstmt.setObject(1, tmpTime4WOTZ, java.sql.Types.TIMESTAMP);
    assertEquals(1, pstmt.executeUpdate());
    pstmt.setObject(1, tmpTime5WOTZ, java.sql.Types.TIMESTAMP);
    assertEquals(1, pstmt.executeUpdate());
    pstmt.setObject(1, tmpTime6WOTZ, java.sql.Types.TIMESTAMP);
    assertEquals(1, pstmt.executeUpdate());
    // Fall through helper
    timestampTestWOTZ();
    assertEquals(30, stmt.executeUpdate("DELETE FROM " + TSWOTZ_TABLE));
    pstmt.close();
    stmt.close();
}

20. MSSQL#create()

Project: railo
Source File: MSSQL.java
View license
@Override
public void create(DatasourceConnection dc, String prefix, int fullPatHash, int pathHash, String path, String name, int type) throws SQLException {
    String sql = "insert into " + prefix + "attrs(rdr_type,rdr_path,rdr_name,rdr_full_path_hash,rdr_path_hash,rdr_last_modified,rdr_mode,rdr_attributes,rdr_data,rdr_length) " + "values(?,?,?,?,?,?,?,?,?,?)";
    //dc.getConnection().prepareStatement(sql);
    PreparedStatement stat = prepareStatement(dc, sql);
    log(sql);
    stat.setInt(1, type);
    stat.setString(2, path);
    stat.setString(3, name);
    stat.setInt(4, fullPatHash);
    stat.setInt(5, pathHash);
    stat.setTimestamp(6, new Timestamp(System.currentTimeMillis()), getCalendar());
    stat.setInt(7, DEFAULT_MODE);
    stat.setInt(8, DEFAULT_ATTRS);
    stat.setInt(9, 0);
    stat.setInt(10, 0);
    //try{
    stat.executeUpdate();
/*}
		finally {
			//DBUtil.closeEL(stat);
		}*/
}

21. MySQL#create()

Project: railo
Source File: MySQL.java
View license
@Override
public void create(DatasourceConnection dc, String prefix, int fullPatHash, int pathHash, String path, String name, int type) throws SQLException {
    String sql = "insert into " + prefix + "attrs(rdr_type,rdr_path,rdr_name,rdr_full_path_hash,rdr_path_hash,rdr_last_modified,rdr_mode,rdr_attributes,rdr_data,rdr_length) " + "values(?,?,?,?,?,?,?,?,?,?)";
    PreparedStatement stat = dc.getConnection().prepareStatement(sql);
    log(sql);
    stat.setInt(1, type);
    stat.setString(2, path);
    stat.setString(3, name);
    stat.setInt(4, fullPatHash);
    stat.setInt(5, pathHash);
    stat.setTimestamp(6, new Timestamp(System.currentTimeMillis()), getCalendar());
    stat.setInt(7, DEFAULT_MODE);
    stat.setInt(8, DEFAULT_ATTRS);
    stat.setInt(9, 0);
    stat.setInt(10, 0);
    try {
        stat.executeUpdate();
    } finally {
        DBUtil.closeEL(stat);
    }
}

22. BatchUpdateTest#testPreparedStatRollbackAndCommitCombinations()

Project: derby
Source File: BatchUpdateTest.java
View license
// try executing batches with various rollback and commit combinations.
public void testPreparedStatRollbackAndCommitCombinations() throws SQLException {
    println("Positive Prepared Stat: batch, rollback," + " batch and commit combinations");
    PreparedStatement pStmt = prepareStatement("insert into t1 values(?)");
    pStmt.setInt(1, 1);
    pStmt.addBatch();
    pStmt.setInt(1, 1);
    pStmt.addBatch();
    /* there were 2 statements in the batch, 
         * update count length should be 2 */
    assertBatchUpdateCounts(new int[] { 1, 1 }, pStmt.executeBatch());
    rollback();
    assertTableRowCount("T1", 0);
    pStmt.setInt(1, 1);
    pStmt.addBatch();
    pStmt.setInt(1, 1);
    pStmt.addBatch();
    /* there were 2 statements in the batch, 
         * update count length should be 2 */
    assertBatchUpdateCounts(new int[] { 1, 1 }, pStmt.executeBatch());
    commit();
    assertTableRowCount("T1", 2);
    // try batch and commit
    println("Positive Prepared Stat: batch and commit combinations");
    pStmt.setInt(1, 1);
    pStmt.addBatch();
    pStmt.setInt(1, 1);
    pStmt.addBatch();
    /* there were 2 statements in the batch, 
         * update count length should be 2 */
    assertBatchUpdateCounts(new int[] { 1, 1 }, pStmt.executeBatch());
    commit();
    assertTableRowCount("T1", 4);
    // try batch, batch and rollback
    println("Positive Prepared Stat: batch, " + "batch and rollback combinations");
    pStmt.setInt(1, 1);
    pStmt.addBatch();
    pStmt.setInt(1, 1);
    pStmt.addBatch();
    /* there were 2 statements in the batch, 
         * update count should be 2 */
    assertBatchUpdateCounts(new int[] { 1, 1 }, pStmt.executeBatch());
    pStmt.setInt(1, 1);
    pStmt.addBatch();
    pStmt.setInt(1, 1);
    pStmt.addBatch();
    /* there were 2 statements in the batch, 
         * update count length should be 2 */
    assertBatchUpdateCounts(new int[] { 1, 1 }, pStmt.executeBatch());
    rollback();
    assertTableRowCount("T1", 4);
    // try batch, batch and commit
    println("Positive Prepared Stat: " + "batch, batch and commit combinations");
    pStmt.setInt(1, 1);
    pStmt.addBatch();
    pStmt.setInt(1, 1);
    pStmt.addBatch();
    /* there were 2 statements in the batch, 
         * update count length should be 2 */
    assertBatchUpdateCounts(new int[] { 1, 1 }, pStmt.executeBatch());
    pStmt.setInt(1, 1);
    pStmt.addBatch();
    pStmt.setInt(1, 1);
    pStmt.addBatch();
    /* there were 2 statements in the batch, 
         * update count length should be 2 */
    assertBatchUpdateCounts(new int[] { 1, 1 }, pStmt.executeBatch());
    commit();
    assertTableRowCount("T1", 8);
    pStmt.close();
    commit();
}

23. Derby6587Test#doImportFromFile()

Project: derby
Source File: Derby6587Test.java
View license
// method which calls the import table, pre-filling some of the values
private void doImportFromFile(String fileName, String toTable) throws SQLException {
    String impsql = "call SYSCS_UTIL.SYSCS_IMPORT_TABLE (? , ? , ? , ?, ? , ?, ?)";
    PreparedStatement ps = prepareStatement(impsql);
    ps.setString(1, "APP");
    ps.setString(2, toTable);
    ps.setString(3, fileName);
    ps.setString(4, null);
    ps.setString(5, null);
    ps.setString(6, null);
    // assuming replace, otherwise this needs to be non-0
    ps.setInt(7, 0);
    ps.execute();
    ps.close();
}

24. ImportExportBaseTest#doImportTable()

Project: derby
Source File: ImportExportBaseTest.java
View license
/**
     * Perform import using SYSCS_UTIL.SYSCS_IMPORT_TABLE procedure.
     */
protected void doImportTable(String schemaName, String tableName, String fileName, String colDel, String charDel, String codeset, int replace) throws SQLException {
    String impsql = "call SYSCS_UTIL.SYSCS_IMPORT_TABLE (?, ?, ?, ?, ?, ?, ?)";
    PreparedStatement ps = prepareStatement(impsql);
    ps.setString(1, schemaName);
    ps.setString(2, tableName);
    ps.setString(3, fileName);
    ps.setString(4, colDel);
    ps.setString(5, charDel);
    ps.setString(6, codeset);
    ps.setInt(7, replace);
    ps.execute();
    ps.close();
}

25. ImportExportBaseTest#doExportTableLobsToExtFile()

Project: derby
Source File: ImportExportBaseTest.java
View license
/**
     * Perform export using 
     * SYSCS_UTIL.SYSCS_EXPORT_TABLE_LOBS_TO_EXTFILE procedure.
     */
protected void doExportTableLobsToExtFile(String schemaName, String tableName, String fileName, String colDel, String charDel, String codeset, String lobsFileName) throws SQLException {
    String expsql = "call SYSCS_UTIL.SYSCS_EXPORT_TABLE_LOBS_TO_EXTFILE" + "(? , ? , ? , ?, ?, ?, ?)";
    PreparedStatement ps = prepareStatement(expsql);
    ps.setString(1, schemaName);
    ps.setString(2, tableName);
    ps.setString(3, fileName);
    ps.setString(4, colDel);
    ps.setString(5, charDel);
    ps.setString(6, codeset);
    ps.setString(7, lobsFileName);
    ps.execute();
    ps.close();
}

26. ImportExportBaseTest#doImportTableLobsFromExtFile()

Project: derby
Source File: ImportExportBaseTest.java
View license
/**
     * Perform import using 
     * SYSCS_UTIL.SYSCS_IMPORT_TABLE_LOBS_FROM_EXTFILE procedure.
     */
protected void doImportTableLobsFromExtFile(String schemaName, String tableName, String fileName, String colDel, String charDel, String codeset, int replace) throws SQLException {
    String impsql = "call SYSCS_UTIL.SYSCS_IMPORT_TABLE_LOBS_FROM_EXTFILE" + "(?, ?, ?, ?, ?, ?, ?)";
    PreparedStatement ps = prepareStatement(impsql);
    ps.setString(1, schemaName);
    ps.setString(2, tableName);
    ps.setString(3, fileName);
    ps.setString(4, colDel);
    ps.setString(5, charDel);
    ps.setString(6, codeset);
    ps.setInt(7, replace);
    ps.execute();
    ps.close();
}

27. ImportExportTest#doImportFromFile()

Project: derby
Source File: ImportExportTest.java
View license
private void doImportFromFile(String fileName, String toSchema, String toTable, String colDel, String charDel, String codeset, int replace) throws SQLException {
    String impsql = "call SYSCS_UTIL.SYSCS_IMPORT_TABLE (? , ? , ? , ?, ? , ?, ?)";
    PreparedStatement ps = prepareStatement(impsql);
    ps.setString(1, toSchema);
    ps.setString(2, toTable);
    ps.setString(3, fileName);
    ps.setString(4, colDel);
    ps.setString(5, charDel);
    ps.setString(6, codeset);
    ps.setInt(7, replace);
    ps.execute();
    ps.close();
}

28. PreparedStatementTest#testTrailingSpaces()

Project: pgjdbc
Source File: PreparedStatementTest.java
View license
public void testTrailingSpaces() throws SQLException {
    PreparedStatement pstmt = con.prepareStatement("INSERT INTO texttable (ch, te, vc) VALUES (?, ?, ?) ");
    String str = "a  ";
    pstmt.setString(1, str);
    pstmt.setString(2, str);
    pstmt.setString(3, str);
    pstmt.executeUpdate();
    pstmt.close();
    pstmt = con.prepareStatement("SELECT ch, te, vc FROM texttable WHERE ch=? AND te=? AND vc=?");
    pstmt.setString(1, str);
    pstmt.setString(2, str);
    pstmt.setString(3, str);
    ResultSet rs = pstmt.executeQuery();
    assertTrue(rs.next());
    assertEquals(str, rs.getString(1));
    assertEquals(str, rs.getString(2));
    assertEquals(str, rs.getString(3));
    rs.close();
    pstmt.close();
}

29. PreparedStatementTest#testTrailingSpaces()

View license
@Test
public void testTrailingSpaces() throws SQLException {
    PreparedStatement pstmt = conn.prepareStatement("INSERT INTO texttable (ch, te, vc) VALUES (?, ?, ?) ");
    String str = "a  ";
    pstmt.setString(1, str);
    pstmt.setString(2, str);
    pstmt.setString(3, str);
    pstmt.executeUpdate();
    pstmt.close();
    pstmt = conn.prepareStatement("SELECT ch, te, vc FROM texttable WHERE ch=? AND te=? AND vc=?");
    pstmt.setString(1, str);
    pstmt.setString(2, str);
    pstmt.setString(3, str);
    ResultSet rs = pstmt.executeQuery();
    assertTrue(rs.next());
    assertEquals(str, rs.getString(1));
    assertEquals(str, rs.getString(2));
    assertEquals(str, rs.getString(3));
    rs.close();
    pstmt.close();
}

30. TestPreparedStatement#testClob()

View license
private void testClob(Connection conn) throws SQLException {
    trace("testClob");
    Statement stat = conn.createStatement();
    PreparedStatement prep;
    ResultSet rs;
    stat.execute("CREATE TABLE T_CLOB(ID INT PRIMARY KEY,V1 CLOB,V2 CLOB)");
    StringBuilder asciiBuffer = new StringBuilder();
    int len = getLength();
    for (int i = 0; i < len; i++) {
        asciiBuffer.append((char) ('a' + (i % 20)));
    }
    String ascii1 = asciiBuffer.toString();
    String ascii2 = "Number2 " + ascii1;
    prep = conn.prepareStatement("INSERT INTO T_CLOB VALUES(?,?,?)");
    prep.setInt(1, 1);
    prep.setString(2, null);
    prep.setNull(3, Types.CLOB);
    prep.executeUpdate();
    prep.clearParameters();
    prep.setInt(1, 2);
    prep.setAsciiStream(2, null, 0);
    prep.setCharacterStream(3, null, 0);
    prep.executeUpdate();
    prep.clearParameters();
    prep.setInt(1, 3);
    prep.setCharacterStream(2, new StringReader(ascii1), ascii1.length());
    prep.setCharacterStream(3, null, 0);
    prep.setAsciiStream(3, new ByteArrayInputStream(ascii2.getBytes()), ascii2.length());
    prep.executeUpdate();
    prep.clearParameters();
    prep.setInt(1, 4);
    prep.setNull(2, Types.CLOB);
    prep.setString(2, ascii2);
    prep.setCharacterStream(3, null, 0);
    prep.setNull(3, Types.CLOB);
    prep.setString(3, ascii1);
    prep.executeUpdate();
    prep.clearParameters();
    prep.setInt(1, 5);
    prep.setObject(2, new StringReader(ascii1));
    prep.setObject(3, new StringReader(ascii2), Types.CLOB, 0);
    prep.executeUpdate();
    rs = stat.executeQuery("SELECT ID, V1, V2 FROM T_CLOB ORDER BY ID");
    rs.next();
    assertEquals(1, rs.getInt(1));
    assertTrue(rs.getCharacterStream(2) == null && rs.wasNull());
    assertTrue(rs.getAsciiStream(3) == null && rs.wasNull());
    rs.next();
    assertEquals(2, rs.getInt(1));
    assertTrue(rs.getString(2) == null && rs.wasNull());
    assertTrue(rs.getString(3) == null && rs.wasNull());
    rs.next();
    assertEquals(3, rs.getInt(1));
    assertEquals(ascii1, rs.getString(2));
    assertEquals(ascii2, rs.getString(3));
    rs.next();
    assertEquals(4, rs.getInt(1));
    assertEquals(ascii2, rs.getString(2));
    assertEquals(ascii1, rs.getString(3));
    rs.next();
    assertEquals(5, rs.getInt(1));
    assertEquals(ascii1, rs.getString(2));
    assertEquals(ascii2, rs.getString(3));
    assertFalse(rs.next());
    assertTrue(prep.getWarnings() == null);
    prep.clearWarnings();
    assertTrue(prep.getWarnings() == null);
    assertTrue(conn == prep.getConnection());
}

31. TradeJdbc#createHolding()

Project: apache-aries
Source File: TradeJdbc.java
View license
private HoldingDataBean createHolding(Connection conn, int accountID, String symbol, double quantity, BigDecimal purchasePrice) throws Exception {
    Timestamp purchaseDate = new Timestamp(System.currentTimeMillis());
    PreparedStatement stmt = getStatement(conn, createHoldingSQL);
    Integer holdingID = KeySequenceDirect.getNextID(conn, "holding", inSession, getInGlobalTxn());
    stmt.setInt(1, holdingID.intValue());
    stmt.setTimestamp(2, purchaseDate);
    stmt.setBigDecimal(3, purchasePrice);
    stmt.setDouble(4, quantity);
    stmt.setString(5, symbol);
    stmt.setInt(6, accountID);
    stmt.executeUpdate();
    stmt.close();
    return getHoldingData(conn, holdingID.intValue());
}

32. TradeJdbc#updateAccountProfile()

Project: apache-aries
Source File: TradeJdbc.java
View license
private void updateAccountProfile(Connection conn, String userID, String password, String fullName, String address, String email, String creditcard) throws Exception {
    PreparedStatement stmt = getStatement(conn, updateAccountProfileSQL);
    stmt.setString(1, password);
    stmt.setString(2, fullName);
    stmt.setString(3, address);
    stmt.setString(4, email);
    stmt.setString(5, creditcard);
    stmt.setString(6, userID);
    stmt.executeUpdate();
    stmt.close();
}

33. TradeJdbc#updateQuotePriceVolume()

Project: apache-aries
Source File: TradeJdbc.java
View license
private void updateQuotePriceVolume(Connection conn, String symbol, BigDecimal newPrice, double newVolume, BigDecimal low, BigDecimal high) throws Exception {
    PreparedStatement stmt = getStatement(conn, updateQuotePriceVolumeSQL);
    stmt.setBigDecimal(1, newPrice);
    stmt.setBigDecimal(2, newPrice);
    stmt.setDouble(3, newVolume);
    stmt.setBigDecimal(4, low);
    stmt.setBigDecimal(5, high);
    stmt.setString(6, symbol);
    stmt.executeUpdate();
    stmt.close();
}

34. TradeJdbc#createHolding()

Project: aries
Source File: TradeJdbc.java
View license
private HoldingDataBean createHolding(Connection conn, int accountID, String symbol, double quantity, BigDecimal purchasePrice) throws Exception {
    Timestamp purchaseDate = new Timestamp(System.currentTimeMillis());
    PreparedStatement stmt = getStatement(conn, createHoldingSQL);
    Integer holdingID = KeySequenceDirect.getNextID(conn, "holding", inSession, getInGlobalTxn());
    stmt.setInt(1, holdingID.intValue());
    stmt.setTimestamp(2, purchaseDate);
    stmt.setBigDecimal(3, purchasePrice);
    stmt.setDouble(4, quantity);
    stmt.setString(5, symbol);
    stmt.setInt(6, accountID);
    stmt.executeUpdate();
    stmt.close();
    return getHoldingData(conn, holdingID.intValue());
}

35. TradeJdbc#updateAccountProfile()

Project: aries
Source File: TradeJdbc.java
View license
private void updateAccountProfile(Connection conn, String userID, String password, String fullName, String address, String email, String creditcard) throws Exception {
    PreparedStatement stmt = getStatement(conn, updateAccountProfileSQL);
    stmt.setString(1, password);
    stmt.setString(2, fullName);
    stmt.setString(3, address);
    stmt.setString(4, email);
    stmt.setString(5, creditcard);
    stmt.setString(6, userID);
    stmt.executeUpdate();
    stmt.close();
}

36. TradeJdbc#updateQuotePriceVolume()

Project: aries
Source File: TradeJdbc.java
View license
private void updateQuotePriceVolume(Connection conn, String symbol, BigDecimal newPrice, double newVolume, BigDecimal low, BigDecimal high) throws Exception {
    PreparedStatement stmt = getStatement(conn, updateQuotePriceVolumeSQL);
    stmt.setBigDecimal(1, newPrice);
    stmt.setBigDecimal(2, newPrice);
    stmt.setDouble(3, newVolume);
    stmt.setBigDecimal(4, low);
    stmt.setBigDecimal(5, high);
    stmt.setString(6, symbol);
    stmt.executeUpdate();
    stmt.close();
}

37. JdbcEventStorageEngine#insertEvent()

View license
@SuppressWarnings("SqlInsertValues")
protected PreparedStatement insertEvent(Connection connection, String table, DomainEventMessage<?> event, Serializer serializer) throws SQLException {
    SerializedObject<?> payload = serializer.serialize(event.getPayload(), dataType);
    SerializedObject<?> metaData = serializer.serialize(event.getMetaData(), dataType);
    final String sql = "INSERT INTO " + table + " (" + String.join(", ", schema.eventIdentifierColumn(), schema.aggregateIdentifierColumn(), schema.sequenceNumberColumn(), schema.typeColumn(), schema.timestampColumn(), schema.payloadTypeColumn(), schema.payloadRevisionColumn(), schema.payloadColumn(), schema.metaDataColumn()) + ") VALUES (?,?,?,?,?,?,?,?,?)";
    // NOSONAR
    PreparedStatement preparedStatement = connection.prepareStatement(sql);
    preparedStatement.setString(1, event.getIdentifier());
    preparedStatement.setString(2, event.getAggregateIdentifier());
    preparedStatement.setLong(3, event.getSequenceNumber());
    preparedStatement.setString(4, event.getType());
    writeTimestamp(preparedStatement, 5, event.getTimestamp());
    preparedStatement.setString(6, payload.getType().getName());
    preparedStatement.setString(7, payload.getType().getRevision());
    preparedStatement.setObject(8, payload.getData());
    preparedStatement.setObject(9, metaData.getData());
    return preparedStatement;
}

38. PrepareStatementTest#testVaryingClientParameterTypeBatch()

Project: derby
Source File: PrepareStatementTest.java
View license
/**
     * Test execution of batch update where the type of
     * a parameter varies for difference entries in the batch.
     */
public void testVaryingClientParameterTypeBatch() throws Exception {
    Statement stmt = createStatement();
    String createSql = "create table varcharclobtab (c1 varchar(100), c2 clob)";
    assertUpdateCount(stmt, 0, createSql);
    stmt.close();
    PreparedStatement pStmt = prepareStatement("insert into varcharclobtab VALUES(?,?)");
    pStmt.setNull(1, java.sql.Types.VARCHAR);
    pStmt.setString(2, "clob");
    pStmt.addBatch();
    pStmt.setString(1, "varchar");
    pStmt.setNull(2, java.sql.Types.CLOB);
    pStmt.addBatch();
    // The following statement should not throw an exception.
    pStmt.executeBatch();
    pStmt.close();
}

39. ParameterMappingTest#testDerby5533GetXXX()

Project: derby
Source File: ParameterMappingTest.java
View license
/**
     * Tests that SQLStates are correct across drivers on rs.getXXX
     * over/underflow.
     * @exception SQLException database access error. Causes test to
     *                         fail with an error.
     */
public void testDerby5533GetXXX() throws SQLException {
    String createTableString = "CREATE TABLE MultiTypeTable (" + "F01 SMALLINT," + "F02 INTEGER," + "F03 BIGINT," + "F04 REAL," + "F05 FLOAT," + "F06 DOUBLE," + "F07 DECIMAL(31)," + "F08 NUMERIC," + "F09 CHAR(100)," + "F10 VARCHAR(256)," + "F11 BOOLEAN)";
    Statement stmt = createStatement();
    stmt.executeUpdate(createTableString);
    PreparedStatement ps = prepareStatement("insert into MultiTypeTable values(?,?,?,?,?,?,?,?,?,?,?)");
    /* First check upper bounds */
    ps.setShort(1, (short) ((short) Byte.MAX_VALUE + 1));
    ps.setInt(2, (int) Short.MAX_VALUE + 1);
    ps.setLong(3, (long) Integer.MAX_VALUE + 1);
    ps.setFloat(4, (float) Long.MAX_VALUE * 10);
    ps.setFloat(5, (float) Long.MAX_VALUE * 10);
    ps.setDouble(6, (double) Float.MAX_VALUE * 10);
    // Largest integer representable in DECIMAL is Derby has 31 digits:
    ps.setBigDecimal(7, new BigDecimal("9999999999999999999999999999999"));
    ps.setInt(8, _X);
    ps.setString(9, " ");
    ps.setString(10, " ");
    ps.setBoolean(11, true);
    ps.executeUpdate();
    PreparedStatement plainSelect = prepareStatement("select * from MultiTypeTable");
    ResultSet rs = plainSelect.executeQuery();
    rs.next();
    // JDBC type -> byte
    assertGetState(rs, "F01", XXX_BYTE, "22003");
    assertGetState(rs, "F02", XXX_BYTE, "22003");
    assertGetState(rs, "F03", XXX_BYTE, "22003");
    assertGetState(rs, "F04", XXX_BYTE, "22003");
    assertGetState(rs, "F05", XXX_BYTE, "22003");
    assertGetState(rs, "F06", XXX_BYTE, "22003");
    assertGetState(rs, "F07", XXX_BYTE, "22003");
    // JDBC type -> short
    assertGetState(rs, "F02", XXX_SHORT, "22003");
    assertGetState(rs, "F03", XXX_SHORT, "22003");
    assertGetState(rs, "F04", XXX_SHORT, "22003");
    assertGetState(rs, "F05", XXX_SHORT, "22003");
    assertGetState(rs, "F06", XXX_SHORT, "22003");
    assertGetState(rs, "F07", XXX_SHORT, "22003");
    // JDBC type -> int
    assertGetState(rs, "F03", XXX_INT, "22003");
    assertGetState(rs, "F04", XXX_INT, "22003");
    assertGetState(rs, "F05", XXX_INT, "22003");
    assertGetState(rs, "F06", XXX_INT, "22003");
    assertGetState(rs, "F07", XXX_INT, "22003");
    // JDBC type -> long
    assertGetState(rs, "F04", XXX_LONG, "22003");
    assertGetState(rs, "F05", XXX_LONG, "22003");
    assertGetState(rs, "F06", XXX_LONG, "22003");
    assertGetState(rs, "F07", XXX_LONG, "22003");
    rs.close();
    // JDBC type -> float
    PreparedStatement uSelect = prepareStatement("SELECT * FROM MultiTypeTable", ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE);
    rs = uSelect.executeQuery();
    rs.next();
    rs.updateDouble("F06", Float.MAX_VALUE * 10.0);
    rs.updateRow();
    rs = plainSelect.executeQuery();
    rs.next();
    assertGetState(rs, "F06", XXX_FLOAT, "22003");
    /* Now check lower bounds */
    PreparedStatement psDelete = prepareStatement("delete from MultiTypeTable");
    psDelete.executeUpdate();
    ps.setShort(1, (short) ((short) Byte.MIN_VALUE - 1));
    ps.setInt(2, (int) Short.MIN_VALUE - 1);
    ps.setLong(3, (long) Integer.MIN_VALUE - 1);
    ps.setFloat(4, -(float) Long.MAX_VALUE * 10);
    ps.setFloat(5, -(float) Long.MAX_VALUE * 10);
    ps.setDouble(6, -(double) Float.MAX_VALUE * 10);
    // Largest integer representable in DECIMAL is Derby has 31 digits:
    ps.setBigDecimal(7, new BigDecimal("-999999999999999999999999999999"));
    ps.setInt(8, _X);
    ps.setString(9, " ");
    ps.setString(10, " ");
    ps.setBoolean(11, false);
    ps.executeUpdate();
    rs = plainSelect.executeQuery();
    rs.next();
    // JDBC type -> byte
    assertGetState(rs, "F01", XXX_BYTE, "22003");
    assertGetState(rs, "F02", XXX_BYTE, "22003");
    assertGetState(rs, "F03", XXX_BYTE, "22003");
    assertGetState(rs, "F04", XXX_BYTE, "22003");
    assertGetState(rs, "F05", XXX_BYTE, "22003");
    assertGetState(rs, "F06", XXX_BYTE, "22003");
    assertGetState(rs, "F07", XXX_BYTE, "22003");
    // JDBC type -> short
    assertGetState(rs, "F02", XXX_SHORT, "22003");
    assertGetState(rs, "F03", XXX_SHORT, "22003");
    assertGetState(rs, "F04", XXX_SHORT, "22003");
    assertGetState(rs, "F05", XXX_SHORT, "22003");
    assertGetState(rs, "F06", XXX_SHORT, "22003");
    assertGetState(rs, "F07", XXX_SHORT, "22003");
    // JDBC type -> int
    assertGetState(rs, "F03", XXX_INT, "22003");
    assertGetState(rs, "F04", XXX_INT, "22003");
    assertGetState(rs, "F05", XXX_INT, "22003");
    assertGetState(rs, "F06", XXX_INT, "22003");
    assertGetState(rs, "F07", XXX_INT, "22003");
    // JDBC type -> long
    assertGetState(rs, "F04", XXX_LONG, "22003");
    assertGetState(rs, "F05", XXX_LONG, "22003");
    assertGetState(rs, "F06", XXX_LONG, "22003");
    // JDBC type -> float
    rs.close();
    rs = uSelect.executeQuery();
    rs.next();
    rs.updateDouble("F06", -Float.MAX_VALUE * 10.0);
    rs.updateRow();
    rs = plainSelect.executeQuery();
    rs.next();
    assertGetState(rs, "F06", XXX_FLOAT, "22003");
}

40. ImportExportBaseTest#doExportTable()

Project: derby
Source File: ImportExportBaseTest.java
View license
/**
     * Perform export using SYSCS_UTIL.SYSCS_EXPORT_TABLE procedure.
     */
protected void doExportTable(String schemaName, String tableName, String fileName, String colDel, String charDel, String codeset) throws SQLException {
    String expsql = "call SYSCS_UTIL.SYSCS_EXPORT_TABLE (? , ? , ? , ?, ? , ?)";
    PreparedStatement ps = prepareStatement(expsql);
    ps.setString(1, schemaName);
    ps.setString(2, tableName);
    ps.setString(3, fileName);
    ps.setString(4, colDel);
    ps.setString(5, charDel);
    ps.setString(6, codeset);
    ps.execute();
    ps.close();
}

41. ImportExportBaseTest#doExportQueryLobsToExtFile()

Project: derby
Source File: ImportExportBaseTest.java
View license
/**
     * Perform export using 
     * SYSCS_UTIL.SYSCS_EXPORT_QUERY_LOBS_TO_EXTFILE procedure.
     */
protected void doExportQueryLobsToExtFile(String query, String fileName, String colDel, String charDel, String codeset, String lobsFileName) throws SQLException {
    String expsql = "call SYSCS_UTIL.SYSCS_EXPORT_QUERY_LOBS_TO_EXTFILE" + "(? , ? , ? , ?, ?, ?)";
    PreparedStatement ps = prepareStatement(expsql);
    ps.setString(1, query);
    ps.setString(2, fileName);
    ps.setString(3, colDel);
    ps.setString(4, charDel);
    ps.setString(5, codeset);
    ps.setString(6, lobsFileName);
    ps.execute();
    ps.close();
}

42. ImportExportTest#doExportToFile()

Project: derby
Source File: ImportExportTest.java
View license
private void doExportToFile(String fileName, String fromSchema, String fromTable, String colDel, String charDel, String codeset) throws SQLException {
    //DERBY-2925: need to delete existing files first.
    if (fileName != null) {
        SupportFilesSetup.deleteFile(fileName);
    }
    String expsql = "call SYSCS_UTIL.SYSCS_EXPORT_TABLE (? , ? , ? , ?, ? , ?)";
    PreparedStatement ps = prepareStatement(expsql);
    ps.setString(1, fromSchema);
    ps.setString(2, fromTable);
    ps.setString(3, fileName);
    ps.setString(4, colDel);
    ps.setString(5, charDel);
    ps.setString(6, codeset);
    ps.execute();
    ps.close();
}

43. PreparedStatementTest#testDouble()

Project: pgjdbc
Source File: PreparedStatementTest.java
View license
public void testDouble() throws SQLException {
    PreparedStatement pstmt = con.prepareStatement("CREATE TEMP TABLE double_tab (max_double float, min_double float, null_value float)");
    pstmt.executeUpdate();
    pstmt.close();
    pstmt = con.prepareStatement("insert into double_tab values (?,?,?)");
    pstmt.setDouble(1, 1.0E125);
    pstmt.setDouble(2, 1.0E-130);
    pstmt.setNull(3, Types.DOUBLE);
    pstmt.executeUpdate();
    pstmt.close();
    pstmt = con.prepareStatement("select * from double_tab");
    ResultSet rs = pstmt.executeQuery();
    assertTrue(rs.next());
    double d = rs.getDouble(1);
    assertTrue(rs.getDouble(1) == 1.0E125);
    assertTrue(rs.getDouble(2) == 1.0E-130);
    rs.getDouble(3);
    assertTrue(rs.wasNull());
    rs.close();
    pstmt.close();
}

44. PreparedStatementTest#testFloat()

Project: pgjdbc
Source File: PreparedStatementTest.java
View license
public void testFloat() throws SQLException {
    PreparedStatement pstmt = con.prepareStatement("CREATE TEMP TABLE float_tab (max_float real, min_float real, null_value real)");
    pstmt.executeUpdate();
    pstmt.close();
    pstmt = con.prepareStatement("insert into float_tab values (?,?,?)");
    pstmt.setFloat(1, (float) 1.0E37);
    pstmt.setFloat(2, (float) 1.0E-37);
    pstmt.setNull(3, Types.FLOAT);
    pstmt.executeUpdate();
    pstmt.close();
    pstmt = con.prepareStatement("select * from float_tab");
    ResultSet rs = pstmt.executeQuery();
    assertTrue(rs.next());
    float f = rs.getFloat(1);
    assertTrue("expected 1.0E37,received " + rs.getFloat(1), rs.getFloat(1) == (float) 1.0E37);
    assertTrue("expected 1.0E-37,received " + rs.getFloat(2), rs.getFloat(2) == (float) 1.0E-37);
    rs.getDouble(3);
    assertTrue(rs.wasNull());
    rs.close();
    pstmt.close();
}

45. PreparedStatementTest#testBoolean()

Project: pgjdbc
Source File: PreparedStatementTest.java
View license
public void testBoolean() throws SQLException {
    PreparedStatement pstmt = con.prepareStatement("CREATE TEMP TABLE bool_tab (max_val boolean, min_val boolean, null_val boolean)");
    pstmt.executeUpdate();
    pstmt.close();
    pstmt = con.prepareStatement("insert into bool_tab values (?,?,?)");
    pstmt.setBoolean(1, true);
    pstmt.setBoolean(2, false);
    pstmt.setNull(3, Types.BIT);
    pstmt.executeUpdate();
    pstmt.close();
    pstmt = con.prepareStatement("select * from bool_tab");
    ResultSet rs = pstmt.executeQuery();
    assertTrue(rs.next());
    assertTrue("expected true,received " + rs.getBoolean(1), rs.getBoolean(1) == true);
    assertTrue("expected false,received " + rs.getBoolean(2), rs.getBoolean(2) == false);
    rs.getFloat(3);
    assertTrue(rs.wasNull());
    rs.close();
    pstmt.close();
}

46. PreparedStatementTest#testDouble()

View license
@Test
public void testDouble() throws SQLException {
    PreparedStatement pstmt = conn.prepareStatement("CREATE TEMP TABLE double_tab (max_double float, min_double float, null_value float)");
    pstmt.executeUpdate();
    pstmt.close();
    pstmt = conn.prepareStatement("insert into double_tab values (?,?,?)");
    pstmt.setDouble(1, 1.0E125);
    pstmt.setDouble(2, 1.0E-130);
    pstmt.setNull(3, Types.DOUBLE);
    pstmt.executeUpdate();
    pstmt.close();
    pstmt = conn.prepareStatement("select * from double_tab");
    ResultSet rs = pstmt.executeQuery();
    assertTrue(rs.next());
    rs.getDouble(1);
    assertTrue(rs.getDouble(1) == 1.0E125);
    assertTrue(rs.getDouble(2) == 1.0E-130);
    rs.getDouble(3);
    assertTrue(rs.wasNull());
    rs.close();
    pstmt.close();
}

47. PreparedStatementTest#testFloat()

View license
@Test
public void testFloat() throws SQLException {
    PreparedStatement pstmt = conn.prepareStatement("CREATE TEMP TABLE float_tab (max_float real, min_float real, null_value real)");
    pstmt.executeUpdate();
    pstmt.close();
    pstmt = conn.prepareStatement("insert into float_tab values (?,?,?)");
    pstmt.setFloat(1, (float) 1.0E37);
    pstmt.setFloat(2, (float) 1.0E-37);
    pstmt.setNull(3, Types.FLOAT);
    pstmt.executeUpdate();
    pstmt.close();
    pstmt = conn.prepareStatement("select * from float_tab");
    ResultSet rs = pstmt.executeQuery();
    assertTrue(rs.next());
    rs.getFloat(1);
    assertTrue("expected 1.0E37,received " + rs.getFloat(1), rs.getFloat(1) == (float) 1.0E37);
    assertTrue("expected 1.0E-37,received " + rs.getFloat(2), rs.getFloat(2) == (float) 1.0E-37);
    rs.getDouble(3);
    assertTrue(rs.wasNull());
    rs.close();
    pstmt.close();
}

48. PreparedStatementTest#testBoolean()

View license
@Test
public void testBoolean() throws SQLException {
    PreparedStatement pstmt = conn.prepareStatement("CREATE TEMP TABLE bool_tab (max_val boolean, min_val boolean, null_val boolean)");
    pstmt.executeUpdate();
    pstmt.close();
    pstmt = conn.prepareStatement("insert into bool_tab values (?,?,?)");
    pstmt.setBoolean(1, true);
    pstmt.setBoolean(2, false);
    pstmt.setNull(3, Types.BIT);
    pstmt.executeUpdate();
    pstmt.close();
    pstmt = conn.prepareStatement("select * from bool_tab");
    ResultSet rs = pstmt.executeQuery();
    assertTrue(rs.next());
    assertTrue("expected true,received " + rs.getBoolean(1), rs.getBoolean(1) == true);
    assertTrue("expected false,received " + rs.getBoolean(2), rs.getBoolean(2) == false);
    rs.getFloat(3);
    assertTrue(rs.wasNull());
    rs.close();
    pstmt.close();
}

49. PreparedStatementTest#testLSeg()

View license
private void testLSeg(String pgtype) throws SQLException {
    PreparedStatement pstmt = conn.prepareStatement("CREATE TEMP TABLE " + pgtype + "_tab (p1 " + pgtype + ", p2 " + pgtype + ", p3 " + pgtype + ")");
    pstmt.executeUpdate();
    pstmt.close();
    pstmt = conn.prepareStatement("insert into " + pgtype + "_tab values (?,?,?)");
    double[] p1 = new double[] { 45.0, 60.0, 40.9, 56.3 };
    double[] p2 = new double[] { 0, 0, 0, 0 };
    pstmt.setObject(1, p1);
    pstmt.setObject(2, p2);
    pstmt.setObject(3, null, Types.OTHER);
    pstmt.executeUpdate();
    pstmt.close();
    pstmt = conn.prepareStatement("select * from " + pgtype + "_tab");
    ResultSet rs = pstmt.executeQuery();
    assertTrue(rs.next());
    assertTrue(rs.getObject(1).getClass() == double[].class);
    assertTrue(Arrays.equals(p1, (double[]) rs.getObject(1)));
    assertTrue(Arrays.equals(p2, (double[]) rs.getObject(2)));
    rs.getObject(3);
    assertTrue(rs.wasNull());
    rs.close();
    pstmt.close();
}

50. TestPreparedStatement#testChangeType()

View license
private static void testChangeType(Connection conn) throws SQLException {
    PreparedStatement prep = conn.prepareStatement("select (? || ? || ?) from dual");
    prep.setString(1, "a");
    prep.setString(2, "b");
    prep.setString(3, "c");
    prep.executeQuery();
    prep.setInt(1, 1);
    prep.setString(2, "ab");
    prep.setInt(3, 45);
    prep.executeQuery();
}

51. DatabaseManager#insertNewBlock()

Project: BlockNanny
Source File: DatabaseManager.java
View license
public void insertNewBlock(String worldID, int worldX, int worldY, int worldZ, String blockID, String playerUUID) throws SQLException {
    PreparedStatement ps = db.prepareStatement("INSERT INTO block_places(world_id, world_x, world_y, world_z, block_id, player_uuid) VALUES(?,?,?,?,?,?);");
    ps.setString(1, worldID);
    ps.setInt(2, worldX);
    ps.setInt(3, worldY);
    ps.setInt(4, worldZ);
    ps.setString(5, blockID);
    ps.setString(6, playerUUID);
    ps.executeUpdate();
}

52. DatabaseManager#updateBlockPosition()

Project: BlockNanny
Source File: DatabaseManager.java
View license
public boolean updateBlockPosition(String worldID, int worldX, int worldY, int worldZ, int newWorldX, int newWorldY, int newWorldZ) throws SQLException {
    PreparedStatement ps = db.prepareStatement("UPDATE block_places SET world_x=?, world_y=?, world_z=? WHERE world_id=? AND world_x=? AND world_y=? AND world_z=?;");
    ps.setInt(1, newWorldX);
    ps.setInt(2, newWorldY);
    ps.setInt(3, newWorldZ);
    ps.setString(4, worldID);
    ps.setInt(5, worldX);
    ps.setInt(6, worldY);
    ps.setInt(7, worldZ);
    int rowsAffected = ps.executeUpdate();
    return rowsAffected > 0;
}

53. EmbedDatabaseMetaData#getExportedKeys()

Project: derby
Source File: EmbedDatabaseMetaData.java
View license
/**
     * Get a description of the foreign key columns that reference a
     * table's primary key columns (the foreign keys exported by a
     * table).  They are ordered by FKTABLE_CAT, FKTABLE_SCHEM,
     * FKTABLE_NAME, and KEY_SEQ.
     *
     * <P>Each foreign key column description has the following columns:
     *  <OL>
     *	<LI><B>PKTABLE_CAT</B> String => primary key table catalog (may be null)
     *	<LI><B>PKTABLE_SCHEM</B> String => primary key table schema (may be null)
     *	<LI><B>PKTABLE_NAME</B> String => primary key table name
     *	<LI><B>PKCOLUMN_NAME</B> String => primary key column name
     *	<LI><B>FKTABLE_CAT</B> String => foreign key table catalog (may be null)
     *      being exported (may be null)
     *	<LI><B>FKTABLE_SCHEM</B> String => foreign key table schema (may be null)
     *      being exported (may be null)
     *	<LI><B>FKTABLE_NAME</B> String => foreign key table name
     *      being exported
     *	<LI><B>FKCOLUMN_NAME</B> String => foreign key column name
     *      being exported
     *	<LI><B>KEY_SEQ</B> short => sequence number within foreign key
     *	<LI><B>UPDATE_RULE</B> short => What happens to
     *       foreign key when primary is updated:
     *      <UL>
     *      <LI> importedNoAction - do not allow update of primary
     *               key if it has been imported
     *      <LI> importedKeyCascade - change imported key to agree
     *               with primary key update
     *      <LI> importedKeySetNull - change imported key to NULL if
     *               its primary key has been updated
     *      <LI> importedKeySetDefault - change imported key to default values
     *               if its primary key has been updated
     *      <LI> importedKeyRestrict - same as importedKeyNoAction
     *                                 (for ODBC 2.x compatibility)
     *      </UL>
     *	<LI><B>DELETE_RULE</B> short => What happens to
     *      the foreign key when primary is deleted.
     *      <UL>
     *      <LI> importedKeyNoAction - do not allow delete of primary
     *               key if it has been imported
     *      <LI> importedKeyCascade - delete rows that import a deleted key
     *      <LI> importedKeySetNull - change imported key to NULL if
     *               its primary key has been deleted
     *      <LI> importedKeyRestrict - same as importedKeyNoAction
     *                                 (for ODBC 2.x compatibility)
     *      <LI> importedKeySetDefault - change imported key to default if
     *               its primary key has been deleted
     *      </UL>
     *	<LI><B>FK_NAME</B> String => foreign key name (may be null)
     *	<LI><B>PK_NAME</B> String => primary key name (may be null)
     *	<LI><B>DEFERRABILITY</B> short => can the evaluation of foreign key
     *      constraints be deferred until commit
     *      <UL>
     *      <LI> importedKeyInitiallyDeferred - see SQL92 for definition
     *      <LI> importedKeyInitiallyImmediate - see SQL92 for definition
     *      <LI> importedKeyNotDeferrable - see SQL92 for definition
     *      </UL>
     *  </OL>
     *
     * @param catalog a catalog name; "" retrieves those without a
     * catalog; null means drop catalog name from the selection criteria
     * @param schema a schema name pattern; "" retrieves those
     * without a schema
     * @param table a table name
     * @return ResultSet - each row is a foreign key column description
     * @see #getImportedKeys
	 * @exception SQLException thrown on failure.
     */
public ResultSet getExportedKeys(String catalog, String schema, String table) throws SQLException {
    if (table == null) {
        throw Util.generateCsSQLException(SQLState.TABLE_NAME_CANNOT_BE_NULL);
    }
    PreparedStatement s = getPreparedQuery("getCrossReference");
    s.setString(1, swapNull(catalog));
    s.setString(2, swapNull(schema));
    //DERBY-1484: Must match table name as stored
    s.setString(3, table);
    s.setString(4, swapNull(null));
    s.setString(5, swapNull(null));
    s.setString(6, swapNull(null));
    return s.executeQuery();
}

54. EmbedDatabaseMetaData#getCrossReference()

Project: derby
Source File: EmbedDatabaseMetaData.java
View license
/**
     * Get a description of the foreign key columns in the foreign key
     * table that reference the primary key columns of the primary key
     * table (describe how one table imports another's key.) This
     * should normally return a single foreign key/primary key pair
     * (most tables only import a foreign key from a table once.)  They
     * are ordered by FKTABLE_CAT, FKTABLE_SCHEM, FKTABLE_NAME, and
     * KEY_SEQ.
     *
     * <P>Each foreign key column description has the following columns:
     *  <OL>
     *	<LI><B>PKTABLE_CAT</B> String => primary key table catalog (may be null)
     *	<LI><B>PKTABLE_SCHEM</B> String => primary key table schema (may be null)
     *	<LI><B>PKTABLE_NAME</B> String => primary key table name
     *	<LI><B>PKCOLUMN_NAME</B> String => primary key column name
     *	<LI><B>FKTABLE_CAT</B> String => foreign key table catalog (may be null)
     *      being exported (may be null)
     *	<LI><B>FKTABLE_SCHEM</B> String => foreign key table schema (may be null)
     *      being exported (may be null)
     *	<LI><B>FKTABLE_NAME</B> String => foreign key table name
     *      being exported
     *	<LI><B>FKCOLUMN_NAME</B> String => foreign key column name
     *      being exported
     *	<LI><B>KEY_SEQ</B> short => sequence number within foreign key
     *	<LI><B>UPDATE_RULE</B> short => What happens to
     *       foreign key when primary is updated:
     *      <UL>
     *      <LI> importedNoAction - do not allow update of primary
     *               key if it has been imported
     *      <LI> importedKeyCascade - change imported key to agree
     *               with primary key update
     *      <LI> importedKeySetNull - change imported key to NULL if
     *               its primary key has been updated
     *      <LI> importedKeySetDefault - change imported key to default values
     *               if its primary key has been updated
     *      <LI> importedKeyRestrict - same as importedKeyNoAction
     *                                 (for ODBC 2.x compatibility)
     *      </UL>
     *	<LI><B>DELETE_RULE</B> short => What happens to
     *      the foreign key when primary is deleted.
     *      <UL>
     *      <LI> importedKeyNoAction - do not allow delete of primary
     *               key if it has been imported
     *      <LI> importedKeyCascade - delete rows that import a deleted key
     *      <LI> importedKeySetNull - change imported key to NULL if
     *               its primary key has been deleted
     *      <LI> importedKeyRestrict - same as importedKeyNoAction
     *                                 (for ODBC 2.x compatibility)
     *      <LI> importedKeySetDefault - change imported key to default if
     *               its primary key has been deleted
     *      </UL>
     *	<LI><B>FK_NAME</B> String => foreign key name (may be null)
     *	<LI><B>PK_NAME</B> String => primary key name (may be null)
     *	<LI><B>DEFERRABILITY</B> short => can the evaluation of foreign key
     *      constraints be deferred until commit
     *      <UL>
     *      <LI> importedKeyInitiallyDeferred - see SQL92 for definition
     *      <LI> importedKeyInitiallyImmediate - see SQL92 for definition
     *      <LI> importedKeyNotDeferrable - see SQL92 for definition
     *      </UL>
     *  </OL>
     *
     * @param primaryCatalog a catalog name; "" retrieves those without a
     * catalog; null means drop catalog name from the selection criteria
     * @param primarySchema a schema name pattern; "" retrieves those
     * without a schema
     * @param primaryTable the table name that exports the key
     * @param foreignCatalog a catalog name; "" retrieves those without a
     * catalog; null means drop catalog name from the selection criteria
     * @param foreignSchema a schema name pattern; "" retrieves those
     * without a schema
     * @param foreignTable the table name that imports the key
     * @return ResultSet - each row is a foreign key column description
     * @see #getImportedKeys
	 * @exception SQLException thrown on failure.
     */
public ResultSet getCrossReference(String primaryCatalog, String primarySchema, String primaryTable, String foreignCatalog, String foreignSchema, String foreignTable) throws SQLException {
    if (primaryTable == null || foreignTable == null) {
        throw Util.generateCsSQLException(SQLState.TABLE_NAME_CANNOT_BE_NULL);
    }
    PreparedStatement s = getPreparedQuery("getCrossReference");
    s.setString(1, swapNull(primaryCatalog));
    s.setString(2, swapNull(primarySchema));
    //JDBC spec: must match table name as stored
    s.setString(3, primaryTable);
    s.setString(4, swapNull(foreignCatalog));
    s.setString(5, swapNull(foreignSchema));
    //JDBC spec: must match table name as stored
    s.setString(6, foreignTable);
    return s.executeQuery();
}

55. EmbedDatabaseMetaData#getCrossReferenceForODBC()

Project: derby
Source File: EmbedDatabaseMetaData.java
View license
/**
     * In contrast to the JDBC version of getCrossReference, this
     * method allows null values for table names.
     */
public ResultSet getCrossReferenceForODBC(String primaryCatalog, String primarySchema, String primaryTable, String foreignCatalog, String foreignSchema, String foreignTable) throws SQLException {
    PreparedStatement s = getPreparedQuery("odbc_getCrossReference");
    s.setString(1, swapNull(primaryCatalog));
    s.setString(2, swapNull(primarySchema));
    s.setString(3, swapNull(primaryTable));
    s.setString(4, swapNull(foreignCatalog));
    s.setString(5, swapNull(foreignSchema));
    s.setString(6, swapNull(foreignTable));
    return s.executeQuery();
}

56. BatchUpdateTest#testAssociatedParams()

Project: derby
Source File: BatchUpdateTest.java
View license
/*
     ** Associated parameters are extra parameters that are created
     ** and associated with the root parameter (the user one) to
     ** improve the performance of like.       For something like
     ** where c1 like ?, we generate extra 'associated' parameters 
     ** that we use for predicates that we give to the access
     ** manager. 
     */
public void testAssociatedParams() throws SQLException {
    Statement stmt = createStatement();
    int i;
    println("Positive Statement: testing associated parameters");
    PreparedStatement checkps = prepareStatement("select x from assocout order by x");
    PreparedStatement ps = prepareStatement("insert into assoc values (?, 'hello')");
    for (i = 10; i < 60; i++) {
        ps.setString(1, Integer.toString(i));
        ps.executeUpdate();
    }
    ps.close();
    ps = prepareStatement("insert into assocout select x from assoc where x like ?");
    ps.setString(1, "33%");
    ps.addBatch();
    ps.setString(1, "21%");
    ps.addBatch();
    ps.setString(1, "49%");
    ps.addBatch();
    assertBatchUpdateCounts(new int[] { 1, 1, 1 }, ps.executeBatch());
    ps.close();
    checkps.execute();
    ResultSet rs = checkps.getResultSet();
    JDBC.assertFullResultSet(rs, new String[][] { { "21" }, { "33" }, { "49" } }, true);
    stmt.executeUpdate("delete from assocout");
    ps = prepareStatement("insert into assocout select x from assoc where x like ?");
    ps.setString(1, "3%");
    // expectedCount 10: values 10-19
    ps.addBatch();
    ps.setString(1, "2%");
    // values 20-29
    ps.addBatch();
    ps.setString(1, "1%");
    // values 30-39
    ps.addBatch();
    // set up expected values for check
    String expectedStrArray[][] = new String[30][1];
    for (i = 10; i < 40; i++) {
        expectedStrArray[i - 10][0] = String.valueOf(i);
    }
    assertBatchUpdateCounts(new int[] { 10, 10, 10 }, ps.executeBatch());
    ps.close();
    checkps.execute();
    rs = checkps.getResultSet();
    JDBC.assertFullResultSet(rs, expectedStrArray, true);
    stmt.executeUpdate("delete from assocout");
    ps = prepareStatement("insert into assocout select x from assoc where x like ?");
    // values 10-59
    ps.setString(1, "%");
    ps.addBatch();
    ps.setString(1, "666666");
    ps.addBatch();
    // values 10-59
    ps.setString(1, "%");
    ps.addBatch();
    // set up expected values for check
    String expectedStrArray2[][] = new String[100][1];
    int j = 0;
    for (i = 10; i < 60; i++) {
        for (int twice = 0; twice < 2; twice++) {
            expectedStrArray2[j][0] = String.valueOf(i);
            j++;
        }
    }
    assertBatchUpdateCounts(new int[] { 50, 0, 50 }, ps.executeBatch());
    ps.close();
    checkps.execute();
    rs = checkps.getResultSet();
    JDBC.assertFullResultSet(rs, expectedStrArray2, true);
    checkps.close();
    stmt.close();
}

57. BatchUpdateTest#testMultipleValueSetPreparedBatch()

Project: derby
Source File: BatchUpdateTest.java
View license
// try executing a batch with 3 different parameter sets in it.
public void testMultipleValueSetPreparedBatch() throws SQLException {
    // try prepared statement batch with just one set of values
    println("Positive Prepared Stat: " + "set 3 set of parameter values and run the batch");
    PreparedStatement pStmt = prepareStatement("insert into t1 values(?)");
    pStmt.setInt(1, 1);
    pStmt.addBatch();
    pStmt.setInt(1, 2);
    pStmt.addBatch();
    pStmt.setInt(1, 3);
    pStmt.addBatch();
    /* 3 parameters were set , update count length should be 3 */
    assertBatchUpdateCounts(new int[] { 1, 1, 1 }, pStmt.executeBatch());
    pStmt.close();
    assertTableRowCount("T1", 3);
    commit();
}

58. BatchUpdateTest#testAutoCommitTruePreparedStatBatch()

Project: derby
Source File: BatchUpdateTest.java
View license
// try prepared statement batch with autocommit true
public void testAutoCommitTruePreparedStatBatch() throws SQLException {
    getConnection().setAutoCommit(true);
    // prepared statement batch with autocommit true
    println("Positive Prepared Stat: testing batch with autocommit true");
    PreparedStatement pStmt = prepareStatement("insert into t1 values(?)");
    pStmt.setInt(1, 1);
    pStmt.addBatch();
    pStmt.setInt(1, 1);
    pStmt.addBatch();
    pStmt.setInt(1, 1);
    pStmt.addBatch();
    /* there were 3 statements in the batch, 
         * update count length should be 3 */
    assertBatchUpdateCounts(new int[] { 1, 1, 1 }, pStmt.executeBatch());
    assertTableRowCount("T1", 3);
    pStmt.close();
}

59. PrepStmtNullTest#testNullClobBlob()

Project: derby
Source File: PrepStmtNullTest.java
View license
/**
     * Test setNull() on Clob/Blob using Varchar/binary types
     *
     * @exception SQLException if error occurs
     */
public void testNullClobBlob() throws SQLException {
    byte[] b2 = new byte[1];
    b2[0] = (byte) 64;
    PreparedStatement pStmt = prepareStatement("insert into ClobBlob values (?,?)");
    pStmt.setNull(1, Types.VARCHAR);
    pStmt.setBytes(2, b2);
    pStmt.execute();
    pStmt.setNull(1, Types.VARCHAR, "");
    pStmt.setBytes(2, b2);
    pStmt.execute();
    pStmt.close();
    Statement stmt1 = createStatement();
    ResultSet rs = stmt1.executeQuery("select * from ClobBlob");
    String[][] expectedRows = new String[][] { { null, bytesToString(b2) }, { null, bytesToString(b2) } };
    JDBC.assertFullResultSet(rs, expectedRows);
    rs.close();
    stmt1.close();
}

60. ResultSetsFromPreparedStatementTest#testGeneratedIdentity()

View license
// Regression tests for DERBY-3343 (regression from the fix for DERBY-827)
/**
     * Private helper method. Runs the same test for different
     * generated identity columns.
     * @param dataType SMALLINT, INT, or BIGINT
     * @param generatedType BY DEFAULT or ALWAYS
     * @throws Exception all errors passed on to JUnit
     */
private void testGeneratedIdentity(String dataType, String generatedType) throws Exception {
    Statement s = createStatement();
    s.execute("CREATE TABLE T(GI " + dataType + " PRIMARY KEY GENERATED " + generatedType + " AS IDENTITY (START WITH 5, INCREMENT BY 10), " + "L VARCHAR(8))");
    PreparedStatement implicit = prepareStatement("INSERT INTO T(L) VALUES('implicit')");
    implicit.executeUpdate();
    implicit.executeUpdate();
    implicit.executeUpdate();
    PreparedStatement explicit = prepareStatement("INSERT INTO T(GI, L) " + "VALUES(DEFAULT, 'explicit')");
    explicit.executeUpdate();
    explicit.executeUpdate();
    explicit.executeUpdate();
}

61. UnaryArithmeticParameterTest#testNOTINWithUnaryMinusAndPlus()

View license
/**
		 * Tests NOT IN with unary minus and unary plus
		 * @throws Exception
		 */
public void testNOTINWithUnaryMinusAndPlus() throws Exception {
    PreparedStatement ps = prepareStatement("select * from t1 where +? not in (-?, +?, 2, ?)");
    ps.setInt(1, -11);
    ps.setInt(2, 1);
    ps.setInt(3, 1);
    ps.setInt(4, 4);
    int[] expectedTypes = new int[] { Types.INTEGER, Types.INTEGER, Types.INTEGER, Types.INTEGER };
    JDBC.assertParameterTypes(ps, expectedTypes);
    Object[][] expectedRows = new Object[][] { { 1, 1, 1.1, new String("abc") }, { -1, -1, -1.0, new String("def") } };
    JDBC.assertFullResultSet(ps.executeQuery(), expectedRows, false);
    ps = prepareStatement("select * from t1 where -? not in (select c21+? from t2)");
    ps.setInt(1, 1);
    ps.setInt(2, 2);
    expectedTypes = new int[] { Types.INTEGER, Types.INTEGER };
    JDBC.assertParameterTypes(ps, expectedTypes);
    JDBC.assertFullResultSet(ps.executeQuery(), expectedRows, false);
    ps.close();
}

62. ImportExportBaseTest#doExportQuery()

Project: derby
Source File: ImportExportBaseTest.java
View license
/**
     * Perform export using SYSCS_UTIL.SYSCS_EXPORT_QUERY procedure.
     */
protected void doExportQuery(String query, String fileName, String colDel, String charDel, String codeset) throws SQLException {
    String expsql = "call SYSCS_UTIL.SYSCS_EXPORT_QUERY(? , ? , ? , ?, ?)";
    PreparedStatement ps = prepareStatement(expsql);
    ps.setString(1, query);
    ps.setString(2, fileName);
    ps.setString(3, colDel);
    ps.setString(4, charDel);
    ps.setString(5, codeset);
    ps.execute();
    ps.close();
}

63. TradeDirect#createHolding()

Project: geronimo
Source File: TradeDirect.java
View license
private HoldingDataBean createHolding(Connection conn, int accountID, String symbol, double quantity, BigDecimal purchasePrice) throws Exception {
    HoldingDataBean holdingData = null;
    Timestamp purchaseDate = new Timestamp(System.currentTimeMillis());
    PreparedStatement stmt = getStatement(conn, createHoldingSQL);
    Integer holdingID = KeySequenceDirect.getNextID(conn, "holding", getInGlobalTxn());
    stmt.setInt(1, holdingID.intValue());
    stmt.setTimestamp(2, purchaseDate);
    stmt.setBigDecimal(3, purchasePrice);
    stmt.setDouble(4, quantity);
    stmt.setString(5, symbol);
    stmt.setInt(6, accountID);
    int rowCount = stmt.executeUpdate();
    stmt.close();
    return getHoldingData(conn, holdingID.intValue());
}

64. TradeDirect#updateAccountProfile()

Project: geronimo
Source File: TradeDirect.java
View license
private void updateAccountProfile(Connection conn, AccountProfileDataBean profileData) throws Exception {
    PreparedStatement stmt = getStatement(conn, updateAccountProfileSQL);
    stmt.setString(1, profileData.getPassword());
    stmt.setString(2, profileData.getFullName());
    stmt.setString(3, profileData.getAddress());
    stmt.setString(4, profileData.getEmail());
    stmt.setString(5, profileData.getCreditCard());
    stmt.setString(6, profileData.getUserID());
    int count = stmt.executeUpdate();
    stmt.close();
}

65. PreparedStatementTest#testDollarQuotesAndIdentifiers()

Project: pgjdbc
Source File: PreparedStatementTest.java
View license
public void testDollarQuotesAndIdentifiers() throws SQLException {
    // dollar-quotes are supported in the backend since version 8.0
    if (!TestUtil.haveMinimumServerVersion(con, "8.0")) {
        return;
    }
    PreparedStatement st;
    con.createStatement().execute("CREATE TEMP TABLE a$b$c(a varchar, b varchar)");
    st = con.prepareStatement("INSERT INTO a$b$c (a, b) VALUES (?, ?)");
    st.setString(1, "a");
    st.setString(2, "b");
    st.executeUpdate();
    st.close();
    con.createStatement().execute("CREATE TEMP TABLE e$f$g(h varchar, e$f$g varchar) ");
    st = con.prepareStatement("UPDATE e$f$g SET h = ? || e$f$g");
    st.setString(1, "a");
    st.executeUpdate();
    st.close();
}

66. PreparedStatementTest#testDollarQuotesAndIdentifiers()

View license
@Test
public void testDollarQuotesAndIdentifiers() throws SQLException {
    PreparedStatement st;
    conn.createStatement().execute("CREATE TEMP TABLE a$b$c(a varchar, b varchar)");
    st = conn.prepareStatement("INSERT INTO a$b$c (a, b) VALUES (?, ?)");
    st.setString(1, "a");
    st.setString(2, "b");
    st.executeUpdate();
    st.close();
    conn.createStatement().execute("CREATE TEMP TABLE e$f$g(h varchar, e$f$g varchar) ");
    st = conn.prepareStatement("UPDATE e$f$g SET h = ? || e$f$g");
    st.setString(1, "a");
    st.executeUpdate();
    st.close();
}

67. TradeJdbc#removeHolding()

Project: apache-aries
Source File: TradeJdbc.java
View license
private void removeHolding(Connection conn, int holdingID, int orderID) throws Exception {
    PreparedStatement stmt = getStatement(conn, removeHoldingSQL);
    stmt.setInt(1, holdingID);
    stmt.executeUpdate();
    stmt.close();
    // set the HoldingID to NULL for the purchase and sell order now that
    // the holding as been removed
    stmt = getStatement(conn, removeHoldingFromOrderSQL);
    stmt.setInt(1, holdingID);
    stmt.executeUpdate();
    stmt.close();
}

68. TradeJdbc#removeHolding()

Project: aries
Source File: TradeJdbc.java
View license
private void removeHolding(Connection conn, int holdingID, int orderID) throws Exception {
    PreparedStatement stmt = getStatement(conn, removeHoldingSQL);
    stmt.setInt(1, holdingID);
    stmt.executeUpdate();
    stmt.close();
    // set the HoldingID to NULL for the purchase and sell order now that
    // the holding as been removed
    stmt = getStatement(conn, removeHoldingFromOrderSQL);
    stmt.setInt(1, holdingID);
    stmt.executeUpdate();
    stmt.close();
}

69. EmbedDatabaseMetaData#doGetIndexInfo()

Project: derby
Source File: EmbedDatabaseMetaData.java
View license
/**
	 * Does the actual work for the getIndexInfo metadata
	 * calls.  See getIndexInfo() method above for parameter
	 * descriptions.
	 * @param queryName Name of the query to execute; is used
	 *	to determine whether the result set should conform to
	 *	JDBC or ODBC specifications.
	 */
private ResultSet doGetIndexInfo(String catalog, String schema, String table, boolean unique, boolean approximate, String queryName) throws SQLException {
    if (table == null) {
        throw Util.generateCsSQLException(SQLState.TABLE_NAME_CANNOT_BE_NULL);
    }
    int approximateInInt = 0;
    if (approximate)
        approximateInInt = 1;
    PreparedStatement s = getPreparedQuery(queryName);
    s.setString(1, swapNull(catalog));
    s.setString(2, swapNull(schema));
    //DERBY-1484: Must match table name as stored
    s.setString(3, table);
    s.setBoolean(4, unique);
    s.setInt(5, approximateInInt);
    return s.executeQuery();
}

70. Bug4356Test#testBug4356()

Project: derby
Source File: Bug4356Test.java
View license
/**
     * Check fix for Bug4356 - Prepared statement parameter buffers are not cleared between calls 
     * to executeUpdate() in the same transaction.
     * Using a prepared statement to insert data into a table using 
     * a sub select to get the data from a second table. The
     * prepared statement doesn't seem to clear it's buffers between 
     * execute statements within the same transaction.
     * @throws SQLException
     */
public void testBug4356() throws SQLException {
    Statement stmt = createStatement();
    ResultSet rs;
    PreparedStatement ps = prepareStatement("INSERT INTO T1 VALUES (?,(select count(*) from t2 where a = ?)) ");
    ps.setInt(1, 1);
    ps.setInt(2, 1);
    ps.executeUpdate();
    ps.setInt(1, 2);
    ps.setInt(2, 2);
    ps.executeUpdate();
    commit();
    rs = stmt.executeQuery("SELECT * FROM T1");
    JDBC.assertFullResultSet(rs, new String[][] { { "1", "1" }, { "2", "0" } });
    rs.close();
    stmt.close();
}

71. DeclareGlobalTempTableJavaTest#testDMLRollback1()

View license
/**
     * Prepared statement test - DML and rollback behavior
     * 
     * @throws SQLException
     */
public void testDMLRollback1() throws SQLException {
    Statement s = createStatement();
    assertUpdateCount(s, 0, "DECLARE GLOBAL TEMPORARY TABLE SESSION.t2(c21 int, c22 int) not logged on commit preserve rows");
    PreparedStatement pStmt = prepareStatement("insert into SESSION.t2 values (?, ?)");
    pStmt.setInt(1, 21);
    pStmt.setInt(2, 1);
    pStmt.execute();
    commit();
    ResultSet rs1 = s.executeQuery("select * from SESSION.t2");
    rs1.next();
    assertEquals(21, rs1.getInt(1));
    assertEquals(1, rs1.getInt(2));
    pStmt.setInt(1, 22);
    pStmt.setInt(2, 2);
    pStmt.execute();
    rollback();
    rs1 = s.executeQuery("select count(*) from SESSION.t2");
    rs1.next();
    assertEquals(0, rs1.getInt(1));
    assertUpdateCount(s, 0, "DROP TABLE SESSION.t2");
}

72. LangProcedureTest#parameter1()

Project: derby
Source File: LangProcedureTest.java
View license
public static void parameter1(int a, String b, String c, java.sql.ResultSet[] rs) throws SQLException {
    Connection conn = DriverManager.getConnection("jdbc:default:connection");
    PreparedStatement ps = conn.prepareStatement("insert into PT1 values (?, ?, ?)");
    ps.setInt(1, a);
    ps.setString(2, b);
    ps.setString(3, c);
    ps.executeUpdate();
    ps.close();
    ps = conn.prepareStatement("select a,b, length(b), c, length(c) from PT1 where a = ?");
    ps.setInt(1, a);
    rs[0] = ps.executeQuery();
    conn.close();
}

73. LangProcedureTest#parameter2()

Project: derby
Source File: LangProcedureTest.java
View license
public static void parameter2(int a, java.math.BigDecimal b, java.math.BigDecimal c, java.sql.ResultSet[] rs) throws SQLException {
    Connection conn = DriverManager.getConnection("jdbc:default:connection");
    PreparedStatement ps = conn.prepareStatement("insert into PT1 values (?, ?, ?)");
    ps.setInt(1, a);
    ps.setString(2, b.toString());
    ps.setString(3, c.toString());
    ps.executeUpdate();
    ps.close();
    ps = conn.prepareStatement("select a,b,c from PT1 where a = ?");
    ps.setInt(1, a);
    rs[0] = ps.executeQuery();
    conn.close();
}

74. LuceneSupportPermsTest#createPoemsTable()

Project: derby
Source File: LuceneSupportPermsTest.java
View license
private void createPoemsTable(Connection conn, int jdbcType) throws Exception {
    goodStatement(conn, "create table poems\n" + "(\n" + "    poemID " + getType(jdbcType) + ",\n" + "    versionStamp int not null,\n" + "    originalAuthor       varchar( 50 ),\n" + "    lastEditor           varchar( 50 ),\n" + "    poemText            clob,\n" + "    constraint poemsKey primary key( poemID, versionStamp )\n" + ")\n");
    PreparedStatement ps = conn.prepareStatement("insert into poems values ( ?, ?, ?, ?, ? )");
    int poemID = 1;
    int versionStamp = 1;
    setNextPoemID(ps, jdbcType, poemID++);
    ps.setInt(2, versionStamp++);
    ps.setString(3, "Geoffrey Chaucer");
    ps.setString(4, "Geoffrey Chaucer");
    ps.setString(5, "Whan that Aprill, with his shoures soote The droghte of March hath perced to the roote And bathed every veyne in swich licour, Of which vertu engendred is the flour;");
    ps.executeUpdate();
    setNextPoemID(ps, jdbcType, poemID++);
    ps.setInt(2, versionStamp++);
    ps.setString(3, "Andrew Marvell");
    ps.setString(4, "Andrew Marvell");
    ps.setString(5, "Had we but world enough, and time, This coyness, lady, were no crime.");
    ps.executeUpdate();
    setNextPoemID(ps, jdbcType, poemID++);
    ps.setInt(2, versionStamp++);
    ps.setString(3, "John Milton");
    ps.setString(4, "John Milton");
    ps.setString(5, "From morn to noon he fell, from noon to dewy eve, a summers day, and with the setting sun dropped from the ze4ith like a falling star on Lemnos, the Aegean isle");
    ps.executeUpdate();
    setNextPoemID(ps, jdbcType, poemID++);
    ps.setInt(2, versionStamp++);
    ps.setString(3, "Lord Byron");
    ps.setString(4, "Lord Byron");
    ps.setString(5, "The Assyrian came down like the wolf on the fold, And his cohorts were gleaming in purple and gold; And the sheen of their spears was like stars on the sea, When the blue wave rolls nightly on deep Galilee.");
    ps.executeUpdate();
    setNextPoemID(ps, jdbcType, poemID++);
    ps.setInt(2, versionStamp++);
    ps.setString(3, "Walt Whitman");
    ps.setString(4, "Walt Whitman");
    ps.setString(5, "When lilacs last in the dooryard bloomd, And the great star early droopd in the western sky in the night, I mournd, and yet shall mourn with ever-returning spring.");
    ps.executeUpdate();
    ps.close();
}

75. NullableUniqueConstraintTest#testMultipartKeyUniqueConstraint()

View license
/**
     * Basic test of Unique Constraint using multipart part key.
     * @throws SQLException
     */
public void testMultipartKeyUniqueConstraint() throws SQLException {
    Connection con = getConnection();
    Statement stmt = con.createStatement();
    //create unique constraint without not null
    stmt.executeUpdate("alter table constraintest add constraint " + "u_con unique (val1, val2, val3)");
    PreparedStatement ps = con.prepareStatement("insert into " + "constraintest (val1, val2, val3, val4) values (?, ?, ?, ?)");
    ps.setString(1, "part1");
    ps.setString(2, "part2");
    ps.setString(3, "part3");
    ps.setString(4, "should pass");
    ps.execute();
    try {
        ps.setString(1, "part1");
        ps.setString(2, "part2");
        ps.setString(3, "part3");
        ps.setString(4, "should fail");
        ps.execute();
        fail("duplicate key inserted expected '23505'");
    } catch (SQLException e) {
        assertSQLState("inserting duplicate", "23505", e);
    }
    ps.setNull(1, Types.VARCHAR);
    ps.setString(2, "part2");
    ps.setString(3, "part3");
    ps.setString(4, "should pass");
    ps.execute();
    ps.setNull(1, Types.VARCHAR);
    ps.setString(2, "part2");
    ps.setString(3, "part3");
    ps.setString(4, "should pass");
    ps.execute();
    ps.setString(1, "part1");
    ps.setNull(2, Types.VARCHAR);
    ps.setString(3, "part3");
    ps.setString(4, "should pass");
    ps.execute();
    //check if there are two record with val1=null
    ResultSet rs = stmt.executeQuery("select count (*) from " + "constraintest where val1 is null");
    rs.next();
    assertEquals("expected 2 rows", 2, rs.getInt(1));
    //try creating constraint with existing value
    stmt.execute("alter table constraintest drop constraint u_con");
    con.commit();
    ps.setString(1, "part1");
    ps.setString(2, "part2");
    ps.setString(3, "part3");
    ps.setString(4, "removeit");
    ps.execute();
    //create constraint - must fail
    try {
        stmt.executeUpdate("alter table constraintest add constraint " + "u_con unique (val1, val2, val3)");
        fail("create unique constraint with duplicate key in " + "table should fail");
    } catch (SQLException e) {
        assertSQLState("creating unique constraint when duplicate" + " keys are present  duplicate", "23505", e);
    }
    //remove duplicate record
    stmt.execute("delete from constraintest where val4 = 'removeit'");
    //should be fine now
    stmt.executeUpdate("alter table constraintest add constraint " + "u_con unique (val1, val2, val3)");
    con.commit();
    stmt.close();
    ps.close();
}

76. SqlBasedRetentionPoc#insertSnapshot()

Project: gobblin
Source File: SqlBasedRetentionPoc.java
View license
private void insertSnapshot(Path snapshotPath) throws Exception {
    String datasetPath = StringUtils.substringBeforeLast(snapshotPath.toString(), Path.SEPARATOR);
    String snapshotName = StringUtils.substringAfterLast(snapshotPath.toString(), Path.SEPARATOR);
    long ts = Long.parseLong(StringUtils.substringBefore(snapshotName, "-PT-"));
    long recordCount = Long.parseLong(StringUtils.substringAfter(snapshotName, "-PT-"));
    PreparedStatement insert = connection.prepareStatement("INSERT INTO Snapshots VALUES (?, ?, ?, ?, ?)");
    insert.setString(1, datasetPath);
    insert.setString(2, snapshotName);
    insert.setString(3, snapshotPath.toString());
    insert.setTimestamp(4, new Timestamp(ts));
    insert.setLong(5, recordCount);
    insert.executeUpdate();
}

77. TestMysqlUnsignedInt#insertNumeric()

Project: otter
Source File: TestMysqlUnsignedInt.java
View license
public static void insertNumeric() throws ClassNotFoundException, SQLException {
    Class.forName("com.mysql.jdbc.Driver");
    Properties from = new Properties();
    from.put("user", "root");
    from.put("password", "root");
    from.put("characterEncoding", "utf8");
    Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/erosa", from);
    PreparedStatement pst = conn.prepareStatement("insert into unsignednumeric(id,id1,id2,id3) values (?,?,?,?)");
    pst.setLong(1, Integer.MAX_VALUE * 2L);
    pst.setLong(2, Integer.MAX_VALUE);
    pst.setBigDecimal(3, new BigDecimal("18446744073709551614"));
    pst.setBigDecimal(4, new BigDecimal("9223372036854775807"));
    pst.executeUpdate();
    pst.close();
    conn.close();
}

78. TestMysqlUnsignedNumber#insertNumeric()

Project: otter
Source File: TestMysqlUnsignedNumber.java
View license
public static void insertNumeric() throws ClassNotFoundException, SQLException {
    Class.forName("com.mysql.jdbc.Driver");
    Properties from = new Properties();
    from.put("user", "root");
    from.put("password", "root");
    from.put("characterEncoding", "utf8");
    Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/erosa", from);
    PreparedStatement pst = conn.prepareStatement("insert into unsignednumeric(id,id1,id2,id3) values (?,?,?,?)");
    pst.setLong(1, Integer.MAX_VALUE * 2L);
    pst.setLong(2, Integer.MIN_VALUE);
    pst.setBigDecimal(3, new BigDecimal("18446744073709551614"));
    pst.setBigDecimal(4, new BigDecimal(Long.MIN_VALUE + ""));
    pst.executeUpdate();
    pst.close();
    conn.close();
}

79. TestCases#testLobDecrypt()

Project: ThriftyPaxos
Source File: TestCases.java
View license
private void testLobDecrypt() throws SQLException {
    Connection conn = getConnection("cases");
    String key = "key";
    String value = "Hello World";
    PreparedStatement prep = conn.prepareStatement("CALL ENCRYPT('AES', RAWTOHEX(?), STRINGTOUTF8(?))");
    prep.setCharacterStream(1, new StringReader(key), -1);
    prep.setCharacterStream(2, new StringReader(value), -1);
    ResultSet rs = prep.executeQuery();
    rs.next();
    String encrypted = rs.getString(1);
    PreparedStatement prep2 = conn.prepareStatement("CALL TRIM(CHAR(0) FROM " + "UTF8TOSTRING(DECRYPT('AES', RAWTOHEX(?), ?)))");
    prep2.setCharacterStream(1, new StringReader(key), -1);
    prep2.setCharacterStream(2, new StringReader(encrypted), -1);
    ResultSet rs2 = prep2.executeQuery();
    rs2.first();
    String decrypted = rs2.getString(1);
    prep2.close();
    assertEquals(value, decrypted);
    conn.close();
}

80. TestPreparedStatement#testTempView()

View license
private void testTempView(Connection conn) throws SQLException {
    Statement stat = conn.createStatement();
    PreparedStatement prep;
    stat.execute("CREATE TABLE TEST(FIELD INT PRIMARY KEY)");
    stat.execute("INSERT INTO TEST VALUES(1)");
    stat.execute("INSERT INTO TEST VALUES(2)");
    prep = conn.prepareStatement("select FIELD FROM " + "(select FIELD FROM (SELECT FIELD  FROM TEST " + "WHERE FIELD = ?) AS T2 " + "WHERE T2.FIELD = ?) AS T3 WHERE T3.FIELD = ?");
    prep.setInt(1, 1);
    prep.setInt(2, 1);
    prep.setInt(3, 1);
    ResultSet rs = prep.executeQuery();
    rs.next();
    assertEquals(1, rs.getInt(1));
    prep.setInt(1, 2);
    prep.setInt(2, 2);
    prep.setInt(3, 2);
    rs = prep.executeQuery();
    rs.next();
    assertEquals(2, rs.getInt(1));
    stat.execute("DROP TABLE TEST");
}

81. TestPreparedStatement#testInsertFunction()

View license
private void testInsertFunction(Connection conn) throws SQLException {
    Statement stat = conn.createStatement();
    PreparedStatement prep;
    ResultSet rs;
    stat.execute("CREATE TABLE TEST(ID INT, H BINARY)");
    prep = conn.prepareStatement("INSERT INTO TEST " + "VALUES(?, HASH('SHA256', STRINGTOUTF8(?), 5))");
    prep.setInt(1, 1);
    prep.setString(2, "One");
    prep.execute();
    prep.setInt(1, 2);
    prep.setString(2, "Two");
    prep.execute();
    rs = stat.executeQuery("SELECT COUNT(DISTINCT H) FROM TEST");
    rs.next();
    assertEquals(2, rs.getInt(1));
    stat.execute("DROP TABLE TEST");
}

82. BootstrapApplierThread#setTabPosition()

Project: databus
Source File: BootstrapApplierThread.java
View license
private void setTabPosition(int srcid, int logid, int tabRid, long windowScn) throws SQLException {
    PreparedStatement stmt = getTabPositionUpdateStmt();
    stmt.setInt(1, logid);
    stmt.setInt(2, tabRid);
    stmt.setLong(3, windowScn);
    stmt.setInt(4, srcid);
    stmt.executeUpdate();
    StringBuilder logLineBuilder = new StringBuilder(1024);
    Formatter logFormatter = new Formatter(logLineBuilder);
    logFormatter.format(APPLIER_STATE_LINE_FORMAT, srcid, logid, tabRid, windowScn);
    log(srcid, logFormatter);
}

83. BootstrapProducerCallback#setLogPosition()

View license
private void setLogPosition(int logid, int logrid, long windowscn, String source) throws SQLException {
    PreparedStatement stmt = getLogPositionStmt();
    stmt.setInt(1, logid);
    stmt.setInt(2, logrid);
    stmt.setLong(3, windowscn);
    stmt.setString(4, source);
    stmt.executeUpdate();
}

84. EmbedDatabaseMetaData#getColumnPrivileges()

Project: derby
Source File: EmbedDatabaseMetaData.java
View license
/**
     * Get a description of the access rights for a table's columns.
     *
     * <P>Only privileges matching the column name criteria are
     * returned.  They are ordered by COLUMN_NAME and PRIVILEGE.
     *
     * <P>Each privilige description has the following columns:
     *  <OL>
     *	<LI><B>TABLE_CAT</B> String => table catalog (may be null)
     *	<LI><B>TABLE_SCHEM</B> String => table schema (may be null)
     *	<LI><B>TABLE_NAME</B> String => table name
     *	<LI><B>COLUMN_NAME</B> String => column name
     *	<LI><B>GRANTOR</B> => grantor of access (may be null)
     *	<LI><B>GRANTEE</B> String => grantee of access
     *	<LI><B>PRIVILEGE</B> String => name of access (SELECT,
     *      INSERT, UPDATE, REFRENCES, ...)
     *	<LI><B>IS_GRANTABLE</B> String => "YES" if grantee is permitted
     *      to grant to others; "NO" if not; null if unknown
     *  </OL>
     *
     * @param catalog a catalog name; "" retrieves those without a
     * catalog; null means drop catalog name from the selection criteria
     * @param schema a schema name; "" retrieves those without a schema
     * @param table a table name
     * @param columnNamePattern a column name pattern
     * @return ResultSet - each row is a column privilege description
     * @see #getSearchStringEscape
	 * @exception SQLException thrown on failure.
     */
public ResultSet getColumnPrivileges(String catalog, String schema, String table, String columnNamePattern) throws SQLException {
    if (table == null) {
        throw Util.generateCsSQLException(SQLState.TABLE_NAME_CANNOT_BE_NULL);
    }
    PreparedStatement s = getPreparedQuery("getColumnPrivileges");
    s.setString(1, swapNull(catalog));
    s.setString(2, swapNull(schema));
    //DERBY-1484; must match table name as stored
    s.setString(3, table);
    s.setString(4, swapNull(columnNamePattern));
    return s.executeQuery();
}

85. CaseI_tr_TRTest#testTurkishIcase()

Project: derby
Source File: CaseI_tr_TRTest.java
View license
/**
     * Test Turkish I casing.  Turkish has two i's. lower case i upper cases 
     * to a upper case i with a dot. Lowercase i with no dot uppercases to I with
     * no dot.
     * @throws SQLException
     */
public void testTurkishIcase() throws SQLException {
    PreparedStatement ps = prepareStatement("values UCASE(?)");
    ps.setString(1, "i");
    //\u0130 is upper case i with a dot
    JDBC.assertSingleValueResultSet(ps.executeQuery(), "?");
    // \u0131 is lower case i no dot
    ps.setString(1, "?");
    JDBC.assertSingleValueResultSet(ps.executeQuery(), "I");
    PreparedStatement ps2 = prepareStatement("values LCASE(?)");
    ps2.setString(1, "I");
    JDBC.assertSingleValueResultSet(ps2.executeQuery(), "?");
    ps2.setString(1, "?");
    JDBC.assertSingleValueResultSet(ps2.executeQuery(), "i");
}

86. CharacterStreamsTest#runTestSetAsciiStreamLongValues()

Project: derby
Source File: CharacterStreamsTest.java
View license
private void runTestSetAsciiStreamLongValues() throws Exception {
    // now insert long values using streams and check them programatically.
    PreparedStatement psi = prepareStatement("insert into charstream(c, vc, lvc, lob) " + "values(?,?,?,?)");
    PreparedStatement psDel = prepareStatement("DELETE FROM charstream");
    PreparedStatement psq2 = prepareStatement("select c, vc, lvc, lob from charstream");
    // now insert long values using streams and check them programatically.
    println("setAsciiStream(LONG ASCII STREAMS)");
    checkAsciiStreams(psDel, psi, psq2, 18, 104, 67, 67);
    checkAsciiStreams(psDel, psi, psq2, 25, 16732, 14563, 14563);
    checkAsciiStreams(psDel, psi, psq2, 1, 32433, 32673, 32673);
    checkAsciiStreams(psDel, psi, psq2, 0, 32532, 32700, 32700);
    psi.close();
    psDel.close();
    psq2.close();
}

87. J2EEDataSourceTest#createFloatStatementForStateChecking()

Project: derby
Source File: J2EEDataSourceTest.java
View license
private PreparedStatement createFloatStatementForStateChecking(int[] parameterExpectedValues, int[] PreparedStatementExpectedValues, Connection conn, String sql) throws SQLException {
    PreparedStatement s = internalCreateFloatStatementForStateChecking(conn, sql);
    s.setCursorName("StokeNewington");
    s.setFetchDirection(ResultSet.FETCH_REVERSE);
    s.setFetchSize(888);
    s.setMaxFieldSize(317);
    s.setMaxRows(91);
    // PreparedStatement Create        
    assertStatementState(parameterExpectedValues, PreparedStatementExpectedValues, s);
    return s;
}

88. LobStreamsTest#setUp()

Project: derby
Source File: LobStreamsTest.java
View license
/**
     * Set up the connection to the database.
     */
public void setUp() throws Exception {
    getConnection().setAutoCommit(false);
    Statement stmt1 = createStatement();
    stmt1.execute("create table testBlobX1 (" + "a integer, " + "b blob(300K), " + "c clob(300K))");
    stmt1.close();
    byte[] b2 = new byte[1];
    b2[0] = (byte) 64;
    String c2 = "c";
    PreparedStatement stmt2 = prepareStatement("INSERT INTO testBlobX1(a, b, c) " + "VALUES (?, ?, ?)");
    stmt2.setInt(1, 1);
    stmt2.setBytes(2, b2);
    stmt2.setString(3, c2);
    stmt2.execute();
    stmt2.close();
}

89. CollationTest2#runDerby5367TestCode()

Project: derby
Source File: CollationTest2.java
View license
/** Runs the core code for the DERBY-5367 test. */
private void runDerby5367TestCode(String table) throws SQLException {
    PreparedStatement sel = prepareStatement("select val from " + table + " where val = 'Test'");
    PreparedStatement ins = prepareStatement("insert into " + table + " values ?");
    ins.setString(1, "Test");
    ins.executeUpdate();
    JDBC.assertFullResultSet(sel.executeQuery(), new String[][] { { "Test" } });
    Statement stmt = createStatement();
    stmt.executeUpdate("delete from " + table + " where val = 'Test'");
    ins.setString(1, "test");
    ins.executeUpdate();
    JDBC.assertFullResultSet(sel.executeQuery(), new String[][] { { "test" } });
    stmt.executeUpdate("delete from " + table);
}

90. TradeDirect#updateQuotePriceVolume()

Project: geronimo
Source File: TradeDirect.java
View license
private void updateQuotePriceVolume(Connection conn, String symbol, BigDecimal newPrice, double newVolume) throws Exception {
    PreparedStatement stmt = getStatement(conn, updateQuotePriceVolumeSQL);
    stmt.setBigDecimal(1, newPrice);
    stmt.setBigDecimal(2, newPrice);
    stmt.setDouble(3, newVolume);
    stmt.setString(4, symbol);
    int count = stmt.executeUpdate();
    stmt.close();
}

91. SQLAccountManager#addOrUpdateAccount()

Project: L2GS
Source File: SQLAccountManager.java
View license
private static void addOrUpdateAccount(String account, String password, String level) throws IOException, SQLException, NoSuchAlgorithmException {
    // Encode Password
    MessageDigest md = MessageDigest.getInstance("SHA");
    byte[] newpass;
    newpass = password.getBytes("UTF-8");
    newpass = md.digest(newpass);
    // Add to Base
    java.sql.Connection con = null;
    con = L2DatabaseFactory.getInstance().getConnection();
    PreparedStatement statement = con.prepareStatement("REPLACE	accounts (login, password, access_level) VALUES (?,?,?)");
    statement.setString(1, account);
    statement.setString(2, Base64.encodeBytes(newpass));
    statement.setString(3, level);
    statement.executeUpdate();
    statement.close();
}

92. SQLAccountManager#addOrUpdateAccount()

View license
private static void addOrUpdateAccount(String account, String password, String level) throws IOException, SQLException, NoSuchAlgorithmException {
    // Encode Password
    MessageDigest md = MessageDigest.getInstance("SHA");
    byte[] newpass;
    newpass = password.getBytes("UTF-8");
    newpass = md.digest(newpass);
    // Add to Base
    java.sql.Connection con = null;
    con = L2DatabaseFactory.getInstance().getConnection();
    PreparedStatement statement = con.prepareStatement("REPLACE	accounts (login, password, accessLevel) VALUES (?,?,?)");
    statement.setString(1, account);
    statement.setString(2, Base64.encodeBytes(newpass));
    statement.setString(3, level);
    statement.executeUpdate();
    statement.close();
}

93. SQLAccountManager#addOrUpdateAccount()

View license
private static void addOrUpdateAccount(String account, String password, String level) throws IOException, SQLException, NoSuchAlgorithmException {
    // Encode Password
    MessageDigest md = MessageDigest.getInstance("SHA");
    byte[] newpass;
    newpass = password.getBytes("UTF-8");
    newpass = md.digest(newpass);
    // Add to Base
    java.sql.Connection con = null;
    con = L2DatabaseFactory.getInstance().getConnection();
    PreparedStatement statement = con.prepareStatement("REPLACE	accounts (login, password, access_level) VALUES (?,?,?)");
    statement.setString(1, account);
    statement.setString(2, Base64.encodeBytes(newpass));
    statement.setString(3, level);
    statement.executeUpdate();
    statement.close();
}

94. DatabaseUpgradeTestUtil#insertGlobalProperty()

View license
public void insertGlobalProperty(String globalProperty, String value) throws SQLException {
    PreparedStatement insert = connection.prepareStatement("insert into global_property (property, property_value, uuid) values (?, ?, ?)");
    insert.setString(1, globalProperty);
    insert.setString(2, value);
    insert.setString(3, UUID.randomUUID().toString());
    insert.executeUpdate();
    insert.close();
    connection.commit();
}

95. GeneratedKeysTest#testBatchGeneratedKeys()

Project: pgjdbc
Source File: GeneratedKeysTest.java
View license
public void testBatchGeneratedKeys() throws SQLException {
    PreparedStatement ps = _conn.prepareStatement("INSERT INTO genkeys(c) VALUES (?)", Statement.RETURN_GENERATED_KEYS);
    ps.setInt(1, 4);
    ps.addBatch();
    ps.setInt(1, 7);
    ps.addBatch();
    ps.executeBatch();
    ResultSet rs = ps.getGeneratedKeys();
    assertTrue(rs.next());
    assertEquals(1, rs.getInt("a"));
    assertTrue(rs.next());
    assertEquals(2, rs.getInt("a"));
    assertTrue(!rs.next());
}

96. PreparedStatementTest#testTimestampTzSetNull()

Project: pgjdbc
Source File: PreparedStatementTest.java
View license
public void testTimestampTzSetNull() throws SQLException {
    PreparedStatement pstmt = con.prepareStatement("INSERT INTO timestamptztable (tstz) VALUES (?)");
    // valid: fully qualified type to setNull()
    pstmt.setNull(1, Types.TIMESTAMP_WITH_TIMEZONE);
    pstmt.executeUpdate();
    // valid: fully qualified type to setObject()
    pstmt.setObject(1, null, Types.TIMESTAMP_WITH_TIMEZONE);
    pstmt.executeUpdate();
    pstmt.close();
}

97. PreparedStatementTest#testTimeTzSetNull()

Project: pgjdbc
Source File: PreparedStatementTest.java
View license
public void testTimeTzSetNull() throws SQLException {
    PreparedStatement pstmt = con.prepareStatement("INSERT INTO timetztable (ttz) VALUES (?)");
    // valid: fully qualified type to setNull()
    pstmt.setNull(1, Types.TIME_WITH_TIMEZONE);
    pstmt.executeUpdate();
    // valid: fully qualified type to setObject()
    pstmt.setObject(1, null, Types.TIME_WITH_TIMEZONE);
    pstmt.executeUpdate();
    pstmt.close();
}

98. PreparedStatementTest#testRowId()

View license
@Test
public void testRowId() throws SQLException {
    PreparedStatement pstmt = conn.prepareStatement("INSERT INTO texttable (te) VALUES (?)", new String[] { "ctid" });
    pstmt.setString(1, "some text");
    pstmt.executeUpdate();
    ResultSet keys = pstmt.getGeneratedKeys();
    assertTrue(keys.next());
    RowId rowId = keys.getRowId(1);
    keys.close();
    pstmt.close();
    pstmt = conn.prepareStatement("SELECT te FROM texttable WHERE ctid = ?");
    pstmt.setRowId(1, rowId);
    ResultSet rs = pstmt.executeQuery();
    assertTrue(rs.next());
    assertEquals("some text", rs.getString(1));
    rs.close();
    pstmt.close();
}

99. PrepStmtTest#colNameAccess()

Project: sqlite-jdbc
Source File: PrepStmtTest.java
View license
@Test
public void colNameAccess() throws SQLException {
    PreparedStatement prep = conn.prepareStatement("select ? as col1, ? as col2, ? as bingo;");
    prep.setNull(1, 0);
    prep.setFloat(2, Float.MIN_VALUE);
    prep.setShort(3, Short.MIN_VALUE);
    prep.executeQuery();
    ResultSet rs = prep.executeQuery();
    assertTrue(rs.next());
    assertNull(rs.getString("col1"));
    assertTrue(rs.wasNull());
    assertEquals(rs.getFloat("col2"), Float.MIN_VALUE, 0.0001);
    assertEquals(rs.getShort("bingo"), Short.MIN_VALUE);
    rs.close();
    prep.close();
}

100. TestResultSet#testDatetimeWithCalendar()

Project: ThriftyPaxos
Source File: TestResultSet.java
View license
private void testDatetimeWithCalendar() throws SQLException {
    trace("Test DATETIME with Calendar");
    ResultSet rs;
    stat.execute("CREATE TABLE TEST(ID INT PRIMARY KEY, " + "D DATE, T TIME, TS TIMESTAMP)");
    PreparedStatement prep = conn.prepareStatement("INSERT INTO TEST VALUES(?, ?, ?, ?)");
    Calendar regular = Calendar.getInstance();
    Calendar other = null;
    // search a locale that has a _different_ raw offset
    long testTime = java.sql.Date.valueOf("2001-02-03").getTime();
    for (String s : TimeZone.getAvailableIDs()) {
        TimeZone zone = TimeZone.getTimeZone(s);
        long rawOffsetDiff = regular.getTimeZone().getRawOffset() - zone.getRawOffset();
        // as for Pacific/Auckland and Etc/GMT+12)
        if (rawOffsetDiff != 0 && rawOffsetDiff != 1000 * 60 * 60 * 24) {
            if (regular.getTimeZone().getOffset(testTime) != zone.getOffset(testTime)) {
                other = Calendar.getInstance(zone);
                break;
            }
        }
    }
    trace("regular offset = " + regular.getTimeZone().getRawOffset() + " other = " + other.getTimeZone().getRawOffset());
    prep.setInt(1, 0);
    prep.setDate(2, null, regular);
    prep.setTime(3, null, regular);
    prep.setTimestamp(4, null, regular);
    prep.execute();
    prep.setInt(1, 1);
    prep.setDate(2, null, other);
    prep.setTime(3, null, other);
    prep.setTimestamp(4, null, other);
    prep.execute();
    prep.setInt(1, 2);
    prep.setDate(2, java.sql.Date.valueOf("2001-02-03"), regular);
    prep.setTime(3, java.sql.Time.valueOf("04:05:06"), regular);
    prep.setTimestamp(4, java.sql.Timestamp.valueOf("2007-08-09 10:11:12.131415"), regular);
    prep.execute();
    prep.setInt(1, 3);
    prep.setDate(2, java.sql.Date.valueOf("2101-02-03"), other);
    prep.setTime(3, java.sql.Time.valueOf("14:05:06"), other);
    prep.setTimestamp(4, java.sql.Timestamp.valueOf("2107-08-09 10:11:12.131415"), other);
    prep.execute();
    prep.setInt(1, 4);
    prep.setDate(2, java.sql.Date.valueOf("2101-02-03"));
    prep.setTime(3, java.sql.Time.valueOf("14:05:06"));
    prep.setTimestamp(4, java.sql.Timestamp.valueOf("2107-08-09 10:11:12.131415"));
    prep.execute();
    rs = stat.executeQuery("SELECT * FROM TEST ORDER BY ID");
    assertResultSetMeta(rs, 4, new String[] { "ID", "D", "T", "TS" }, new int[] { Types.INTEGER, Types.DATE, Types.TIME, Types.TIMESTAMP }, new int[] { 10, 8, 6, 23 }, new int[] { 0, 0, 0, 10 });
    rs.next();
    assertEquals(0, rs.getInt(1));
    assertTrue(rs.getDate(2, regular) == null && rs.wasNull());
    assertTrue(rs.getTime(3, regular) == null && rs.wasNull());
    assertTrue(rs.getTimestamp(3, regular) == null && rs.wasNull());
    rs.next();
    assertEquals(1, rs.getInt(1));
    assertTrue(rs.getDate(2, other) == null && rs.wasNull());
    assertTrue(rs.getTime(3, other) == null && rs.wasNull());
    assertTrue(rs.getTimestamp(3, other) == null && rs.wasNull());
    rs.next();
    assertEquals(2, rs.getInt(1));
    assertEquals("2001-02-03", rs.getDate(2, regular).toString());
    assertEquals("04:05:06", rs.getTime(3, regular).toString());
    assertFalse(rs.getTime(3, other).toString().equals("04:05:06"));
    assertEquals("2007-08-09 10:11:12.131415", rs.getTimestamp(4, regular).toString());
    assertFalse(rs.getTimestamp(4, other).toString().equals("2007-08-09 10:11:12.131415"));
    rs.next();
    assertEquals(3, rs.getInt("ID"));
    assertFalse(rs.getTimestamp("TS", regular).toString().equals("2107-08-09 10:11:12.131415"));
    assertEquals("2107-08-09 10:11:12.131415", rs.getTimestamp("TS", other).toString());
    assertFalse(rs.getTime("T", regular).toString().equals("14:05:06"));
    assertEquals("14:05:06", rs.getTime("T", other).toString());
    // checkFalse(rs.getDate(2, regular).toString(), "2101-02-03");
    // check(rs.getDate("D", other).toString(), "2101-02-03");
    rs.next();
    assertEquals(4, rs.getInt("ID"));
    assertEquals("2107-08-09 10:11:12.131415", rs.getTimestamp("TS").toString());
    assertEquals("14:05:06", rs.getTime("T").toString());
    assertEquals("2101-02-03", rs.getDate("D").toString());
    assertFalse(rs.next());
    stat.execute("DROP TABLE TEST");
}