public void provideAllPrivToAll(Connection dConn, Connection gConn) {
   ArrayList<SQLException> exList = new ArrayList<SQLException>();
   for (int i = 0; i < tableNames.length; i++) {
     StringBuffer sql = new StringBuffer();
     sql.append("grant all privileges on " + tableNames[i] + " to " + getAllGrantees());
     Log.getLogWriter().info("security statement is " + sql.toString());
     if (dConn != null) {
       try {
         Statement stmt = dConn.createStatement();
         stmt.execute(sql.toString()); // execute authorization
         dConn.commit();
         stmt.close();
       } catch (SQLException se) {
         SQLHelper.handleDerbySQLException(se, exList);
       }
       try {
         Statement stmt = gConn.createStatement();
         stmt.execute(sql.toString()); // execute authorization
         gConn.commit();
         stmt.close();
       } catch (SQLException se) {
         SQLHelper.handleGFGFXDException(se, exList);
       }
     } else {
       try {
         Statement stmt = gConn.createStatement();
         stmt.execute(sql.toString()); // execute authorization
         gConn.commit();
         stmt.close();
       } catch (SQLException se) {
         SQLHelper.handleSQLException(se);
       }
     }
   }
 }
 private void revokeDelegatedPrivilege(Connection dConn, Connection gConn, String tableName) {
   int num = SQLTest.random.nextInt(SQLTest.numOfWorkers) + 1;
   ArrayList<SQLException> exceptionList = new ArrayList<SQLException>();
   String grantees = getGrantees(num);
   StringBuffer sql = new StringBuffer();
   int whichPriv = SQLTest.random.nextInt(tablePriv.length);
   sql.append("revoke " + tablePriv[whichPriv] + " on " + tableName + " from " + grantees);
   Log.getLogWriter().info("security statement is " + sql.toString());
   try {
     Statement stmt = dConn.createStatement();
     stmt.execute(sql.toString()); // execute authorization
     dConn.commit();
     stmt.close();
   } catch (SQLException se) {
     SQLHelper.handleDerbySQLException(se, exceptionList);
   }
   try {
     Statement stmt = gConn.createStatement();
     stmt.execute(sql.toString()); // execute authorization
     gConn.commit();
     stmt.close();
   } catch (SQLException se) {
     SQLHelper.handleGFGFXDException(se, exceptionList);
   }
 }
  //
  // Examine BLOBs and CLOBs.
  //
  private void vetLargeObjects(
      Connection conn, HashSet<String> unsupportedList, HashSet<String> notUnderstoodList)
      throws Exception {
    Statement stmt = conn.createStatement();

    stmt.execute("CREATE TABLE t (id INT PRIMARY KEY, " + "b BLOB(10), c CLOB(10))");
    stmt.execute(
        "INSERT INTO t (id, b, c) VALUES (1, "
            + "CAST ("
            + TestUtil.stringToHexLiteral("101010001101")
            + "AS BLOB(10)), CAST ('hello' AS CLOB(10)))");

    ResultSet rs = stmt.executeQuery("SELECT id, b, c FROM t");

    rs.next();

    Blob blob = rs.getBlob(2);
    Clob clob = rs.getClob(3);

    vetObject(blob, unsupportedList, notUnderstoodList);
    vetObject(clob, unsupportedList, notUnderstoodList);

    stmt.close();
    conn.rollback();
  }
Example #4
0
  public void t1estDataSource() {
    Connection con = null;
    Statement st = null;
    try {
      P6TestUtil.unloadDrivers();

      // try to do a simple test using the datasourcey stuff
      Properties props = P6TestUtil.loadProperties("P6Test.properties");
      String user = props.getProperty("user");
      String password = props.getProperty("password");
      String url = props.getProperty("url");

      P6DriverManagerDataSource ds = new P6DriverManagerDataSource();

      ds.setUrl(url);

      con = ds.getConnection(user, password);
      st = con.createStatement();
      st.execute("create table foo (col1 varchar2(255))");
      st.execute("insert into table foo values ('1')");

      ResultSet rs = st.executeQuery("select count(*) from foo");
      // assertTrue(rs.

    } catch (Exception e) {
      e.printStackTrace(System.out);
      fail("unexpected exception: " + e);
    } finally {

    }
  }
Example #5
0
 /** Test batched callable statements where the call has no parameters. */
 public void testCallStmtNoParams() throws Exception {
   dropProcedure("jTDS_PROC");
   try {
     Statement stmt = con.createStatement();
     stmt.execute("create table #testbatch (id numeric(10) identity, data varchar(255))");
     stmt.execute(
         "create proc jTDS_PROC  as " + "INSERT INTO #testbatch (data) VALUES ('same each time')");
     CallableStatement cstmt = con.prepareCall("{call jTDS_PROC}");
     for (int i = 0; i < 5; i++) {
       cstmt.addBatch();
     }
     int x[];
     try {
       x = cstmt.executeBatch();
     } catch (BatchUpdateException e) {
       x = e.getUpdateCounts();
     }
     assertEquals(5, x.length);
     assertEquals(1, x[0]);
     assertEquals(1, x[1]);
     assertEquals(1, x[2]);
     assertEquals(1, x[3]);
     assertEquals(1, x[4]);
   } finally {
     dropProcedure("jTDS_PROC");
   }
 }
Example #6
0
 /**
  * Test batched callable statements where the call includes literal parameters which prevent the
  * use of RPC calls.
  */
 public void testCallStmtBatch2() throws Exception {
   dropProcedure("jTDS_PROC");
   try {
     Statement stmt = con.createStatement();
     stmt.execute("create table #testbatch (id int, data varchar(255))");
     stmt.execute(
         "create proc jTDS_PROC @p1 varchar(10), @p2 varchar(255) as "
             + "INSERT INTO #testbatch VALUES (convert(int, @p1), @p2)");
     CallableStatement cstmt = con.prepareCall("{call jTDS_PROC (?, 'literal parameter')}");
     for (int i = 0; i < 5; i++) {
       if (i == 2) {
         cstmt.setString(1, "XXX");
       } else {
         cstmt.setString(1, Integer.toString(i));
       }
       cstmt.addBatch();
     }
     int x[];
     try {
       x = cstmt.executeBatch();
     } catch (BatchUpdateException e) {
       x = e.getUpdateCounts();
     }
     if (con.getMetaData().getDatabaseProductName().toLowerCase().startsWith("microsoft")) {
       assertEquals(5, x.length);
       assertEquals(1, x[0]);
       assertEquals(1, x[1]);
       assertEquals(EXECUTE_FAILED, x[2]);
       assertEquals(EXECUTE_FAILED, x[3]);
       assertEquals(EXECUTE_FAILED, x[4]);
     } else {
       assertEquals(5, x.length);
       assertEquals(1, x[0]);
       assertEquals(1, x[1]);
       assertEquals(EXECUTE_FAILED, x[2]);
       assertEquals(1, x[3]);
       assertEquals(1, x[4]);
     }
     // Now without errors
     stmt.execute("TRUNCATE TABLE #testbatch");
     for (int i = 0; i < 5; i++) {
       cstmt.setString(1, Integer.toString(i));
       cstmt.addBatch();
     }
     try {
       x = cstmt.executeBatch();
     } catch (BatchUpdateException e) {
       x = e.getUpdateCounts();
     }
     assertEquals(5, x.length);
     assertEquals(1, x[0]);
     assertEquals(1, x[1]);
     assertEquals(1, x[2]);
     assertEquals(1, x[3]);
     assertEquals(1, x[4]);
   } finally {
     dropProcedure("jTDS_PROC");
   }
 }
Example #7
0
 /** Test batched prepared statements. */
 public void testPrepStmtBatch() throws Exception {
   Statement stmt = con.createStatement();
   stmt.execute("create table #testbatch (id int, data varchar(255))");
   PreparedStatement pstmt = con.prepareStatement("INSERT INTO #testbatch VALUES (?, ?)");
   for (int i = 0; i < 5; i++) {
     if (i == 2) {
       pstmt.setString(1, "xxx");
     } else {
       pstmt.setInt(1, i);
     }
     pstmt.setString(2, "This is line " + i);
     pstmt.addBatch();
   }
   int x[];
   try {
     x = pstmt.executeBatch();
   } catch (BatchUpdateException e) {
     x = e.getUpdateCounts();
   }
   if (con.getMetaData().getDatabaseProductName().toLowerCase().startsWith("microsoft")) {
     assertEquals(5, x.length);
     assertEquals(1, x[0]);
     assertEquals(1, x[1]);
     assertEquals(EXECUTE_FAILED, x[2]);
     assertEquals(EXECUTE_FAILED, x[3]);
     assertEquals(EXECUTE_FAILED, x[4]);
   } else {
     // Sybase - Entire batch fails due to data conversion error
     // detected in statement 3
     assertEquals(5, x.length);
     assertEquals(EXECUTE_FAILED, x[0]);
     assertEquals(EXECUTE_FAILED, x[1]);
     assertEquals(EXECUTE_FAILED, x[2]);
     assertEquals(EXECUTE_FAILED, x[3]);
     assertEquals(EXECUTE_FAILED, x[4]);
   }
   // Now without errors
   stmt.execute("TRUNCATE TABLE #testbatch");
   for (int i = 0; i < 5; i++) {
     pstmt.setInt(1, i);
     pstmt.setString(2, "This is line " + i);
     pstmt.addBatch();
   }
   x = pstmt.executeBatch();
   assertEquals(5, x.length);
   assertEquals(1, x[0]);
   assertEquals(1, x[1]);
   assertEquals(1, x[2]);
   assertEquals(1, x[3]);
   assertEquals(1, x[4]);
 }
 public void resetStore() throws BlockStoreException {
   maybeConnect();
   try {
     Statement s = conn.get().createStatement();
     s.execute("DROP TABLE settings");
     s.execute("DROP TABLE headers");
     s.execute("DROP TABLE undoableBlocks");
     s.execute("DROP TABLE openOutputs");
     s.close();
     createTables();
     initFromDatabase();
   } catch (SQLException ex) {
     throw new RuntimeException(ex);
   }
 }
Example #9
0
 /** Test batched statements. */
 public void testBatch() throws Exception {
   Statement stmt = con.createStatement();
   stmt.execute("create table #testbatch (id int, data varchar(255))");
   for (int i = 0; i < 5; i++) {
     if (i == 2) {
       // This statement will generate an error
       stmt.addBatch("INSERT INTO #testbatch VALUES ('xx', 'This is line " + i + "')");
     } else {
       stmt.addBatch("INSERT INTO #testbatch VALUES (" + i + ", 'This is line " + i + "')");
     }
   }
   int x[];
   try {
     x = stmt.executeBatch();
   } catch (BatchUpdateException e) {
     x = e.getUpdateCounts();
   }
   if (con.getMetaData().getDatabaseProductName().toLowerCase().startsWith("microsoft")
       && ((JtdsDatabaseMetaData) con.getMetaData()).getDatabaseMajorVersion() > 6) {
     assertEquals(5, x.length);
     assertEquals(1, x[0]);
     assertEquals(1, x[1]);
     assertEquals(EXECUTE_FAILED, x[2]);
     assertEquals(EXECUTE_FAILED, x[3]);
     assertEquals(EXECUTE_FAILED, x[4]);
   } else {
     // Sybase or SQL Server 6.5 - Entire batch fails due to data conversion error
     // detected in statement 3
     assertEquals(5, x.length);
     assertEquals(EXECUTE_FAILED, x[0]);
     assertEquals(EXECUTE_FAILED, x[1]);
     assertEquals(EXECUTE_FAILED, x[2]);
     assertEquals(EXECUTE_FAILED, x[3]);
     assertEquals(EXECUTE_FAILED, x[4]);
   }
   // Now without errors
   stmt.execute("TRUNCATE TABLE #testbatch");
   for (int i = 0; i < 5; i++) {
     stmt.addBatch("INSERT INTO #testbatch VALUES (" + i + ", 'This is line " + i + "')");
   }
   x = stmt.executeBatch();
   assertEquals(5, x.length);
   assertEquals(1, x[0]);
   assertEquals(1, x[1]);
   assertEquals(1, x[2]);
   assertEquals(1, x[3]);
   assertEquals(1, x[4]);
 }
Example #10
0
  /**
   * Test batched prepared statement concurrency. Batch prepares must not disappear between the
   * moment when they were created and when they are executed.
   */
  public void testConcurrentBatching() throws Exception {
    // Create a connection with a batch size of 1. This should cause prepares and actual batch
    // execution to become
    // interspersed (if correct synchronization is not in place) and greatly increase the chance of
    // prepares
    // being rolled back before getting executed.
    Properties props = new Properties();
    props.setProperty(Messages.get(net.sourceforge.jtds.jdbc.Driver.BATCHSIZE), "1");
    props.setProperty(
        Messages.get(net.sourceforge.jtds.jdbc.Driver.PREPARESQL),
        String.valueOf(TdsCore.TEMPORARY_STORED_PROCEDURES));
    Connection con = getConnection(props);

    try {
      Statement stmt = con.createStatement();
      stmt.execute(
          "create table #testConcurrentBatch (v1 int, v2 int, v3 int, v4 int, v5 int, v6 int)");
      stmt.close();

      Vector exceptions = new Vector();
      con.setAutoCommit(false);

      Thread t1 = new ConcurrentBatchingHelper(con, exceptions);
      Thread t2 = new ConcurrentBatchingHelper(con, exceptions);
      t1.start();
      t2.start();
      t1.join();
      t2.join();

      assertEquals(0, exceptions.size());
    } finally {
      con.close();
    }
  }
  // execute and get results
  private void execute(Connection conn, String text, Writer writer, boolean commaSeparator)
      throws SQLException {

    BufferedWriter buffer = new BufferedWriter(writer);
    Statement stmt = conn.createStatement();
    stmt.execute(text);
    ResultSet rs = stmt.getResultSet();
    ResultSetMetaData metadata = rs.getMetaData();
    int nbCols = metadata.getColumnCount();
    String[] labels = new String[nbCols];
    int[] colwidths = new int[nbCols];
    int[] colpos = new int[nbCols];
    int linewidth = 1;

    // read each occurrence
    try {
      while (rs.next()) {
        for (int i = 0; i < nbCols; i++) {
          Object value = rs.getObject(i + 1);
          if (value != null) {
            buffer.write(value.toString());
            if (commaSeparator) buffer.write(",");
          }
        }
      }
      buffer.flush();
      rs.close();
    } catch (IOException ex) {
      if (Debug.isDebug()) ex.printStackTrace();
      // ok, exit from the loop
    } catch (SQLException ex) {
      if (Debug.isDebug()) ex.printStackTrace();
    }
  }
 protected void applySecurityToGFE(Connection gConn, String sql) {
   Log.getLogWriter().info("execute authorization statement in GFE");
   Log.getLogWriter().info("security statement is: " + sql);
   try {
     Statement stmt = gConn.createStatement();
     stmt.execute(sql); // execute authorization
   } catch (SQLException se) {
     if (se.getSQLState().equals("42506") && SQLTest.testSecurity)
       Log.getLogWriter()
           .info("Got the expected exception for authorization," + " continuing tests");
     else if (se.getSQLState().equals("42509") && SQLTest.testSecurity)
       Log.getLogWriter()
           .info(
               "Got the expected grant or revoke operation "
                   + "is not allowed exception for authorization,"
                   + " continuing tests");
     else if (se.getSQLState().equals("42Y03") && hasRoutine)
       Log.getLogWriter()
           .info(
               "Got the expected not recognized as "
                   + "a function or procedure exception for authorization,"
                   + " continuing tests");
     else SQLHelper.handleSQLException(se);
   }
 }
Example #13
0
 private void checkDatabaseContents(String query, String[][] correct) throws Exception {
   Connection con2 = TestUtil.openDB();
   Statement s = con2.createStatement();
   assertFalse(s.execute("set time zone 'UTC'"));
   assertTrue(s.execute(query));
   ResultSet rs = s.getResultSet();
   for (int j = 0; j < correct.length; ++j) {
     assertTrue(rs.next());
     for (int i = 0; i < correct[j].length; ++i) {
       assertEquals("On row " + (j + 1), correct[j][i], rs.getString(i + 1));
     }
   }
   assertFalse(rs.next());
   rs.close();
   s.close();
   con2.close();
 }
Example #14
0
 /** Test for bug [1180169] JDBC escapes not allowed with Sybase addBatch. */
 public void testBatchEsc() throws Exception {
   Statement stmt = con.createStatement();
   stmt.execute("CREATE TABLE #TESTBATCH (ts datetime)");
   stmt.addBatch("INSERT INTO #TESTBATCH VALUES ({ts '1999-01-01 23:50:00'})");
   int counts[] = stmt.executeBatch();
   assertEquals(1, counts[0]);
   stmt.close();
 }
  /** Method declaration Adjust this method for large strings...ie multi megabtypes. */
  void execute() {

    String sCmd = null;

    if (4096 <= ifHuge.length()) {
      sCmd = ifHuge;
    } else {
      sCmd = txtCommand.getText();
    }

    if (sCmd.startsWith("-->>>TEST<<<--")) {
      testPerformance();

      return;
    }

    String g[] = new String[1];

    lTime = System.currentTimeMillis();

    try {
      sStatement.execute(sCmd);

      lTime = System.currentTimeMillis() - lTime;

      int r = sStatement.getUpdateCount();

      if (r == -1) {
        formatResultSet(sStatement.getResultSet());
      } else {
        g[0] = "update count";

        gResult.setHead(g);

        g[0] = String.valueOf(r);

        gResult.addRow(g);
      }

      addToRecent(txtCommand.getText());
    } catch (SQLException e) {
      lTime = System.currentTimeMillis() - lTime;
      g[0] = "SQL Error";

      gResult.setHead(g);

      String s = e.getMessage();

      s += " / Error Code: " + e.getErrorCode();
      s += " / State: " + e.getSQLState();
      g[0] = s;

      gResult.addRow(g);
    }

    updateResult();
    System.gc();
  }
 protected void applySecurityToGFE(Connection gConn, String sql, ArrayList<SQLException> exList) {
   Log.getLogWriter().info("execute authorization statement in GFE");
   Log.getLogWriter().info("security statement is: " + sql);
   try {
     Statement stmt = gConn.createStatement();
     stmt.execute(sql); // execute authorization stmt
   } catch (SQLException se) {
     SQLHelper.handleGFGFXDException(se, exList);
   }
 }
Example #17
0
 public static void main(String args[]) throws ParseException {
   SLParser parser = new SLParser(System.in);
   List<Statement> program = parser.stmntList();
   for (Statement stmnt : program) {
     System.out.println(stmnt);
   }
   for (Statement stmnt : program) {
     stmnt.execute();
   }
 }
Example #18
0
  public static void setupDb() {
    loadDriver();
    Connection conn = null;
    ArrayList statements = new ArrayList();
    Statement s = null;
    ResultSet rs = null;
    try {
      // database name
      String dbName = "demoDB";

      conn = DriverManager.getConnection(protocol + dbName + ";create=true", props);

      System.out.println("Creating database " + dbName);
      boolean createTable = false;
      s = conn.createStatement();
      try {
        s.executeQuery("SELECT count(*) FROM rssFeed");
      } catch (Exception e) {
        createTable = true;
      }

      if (createTable) {

        // handle transaction
        conn.setAutoCommit(false);

        s = conn.createStatement();
        statements.add(s);

        // Create a contact table...
        s.execute("create table rssFeed(id int, title varchar(255), url varchar(600))");
        System.out.println("Created table rssFeed ");

        conn.commit();
      }

      shutdown();
    } catch (SQLException sqle) {
      sqle.printStackTrace();
    } finally {

      close(rs);

      // Statements and PreparedStatements
      int i = 0;
      while (!statements.isEmpty()) {
        // PreparedStatement extend Statement
        Statement st = (Statement) statements.remove(i);
        close(st);
      }

      close(conn);
    }
  }
Example #19
0
 public void testHalfHourTimezone() throws Exception {
   Statement stmt = con.createStatement();
   stmt.execute("SET TimeZone = 'GMT+3:30'");
   for (int i = 0; i < PREPARE_THRESHOLD; i++) {
     PreparedStatement ps = con.prepareStatement("SELECT '1969-12-31 20:30:00'::timestamptz");
     ResultSet rs = ps.executeQuery();
     assertTrue(rs.next());
     assertEquals(0L, rs.getTimestamp(1).getTime());
     ps.close();
   }
 }
  /** Business logic to execute. */
  public VOResponse deleteCharges(ArrayList list, String serverLanguageId, String username)
      throws Throwable {
    Statement stmt = null;
    Connection conn = null;
    try {
      if (this.conn == null) conn = getConn();
      else conn = this.conn;
      stmt = conn.createStatement();

      ChargeVO vo = null;
      for (int i = 0; i < list.size(); i++) {
        // logically delete the record in SAL06...
        vo = (ChargeVO) list.get(i);
        stmt.execute(
            "update SAL06_CHARGES set ENABLED='N' where COMPANY_CODE_SYS01='"
                + vo.getCompanyCodeSys01SAL06()
                + "' and CHARGE_CODE='"
                + vo.getChargeCodeSAL06()
                + "'");
      }

      return new VOResponse(new Boolean(true));
    } catch (Throwable ex) {
      Logger.error(
          username,
          this.getClass().getName(),
          "executeCommand",
          "Error while deleting existing charges",
          ex);
      try {
        if (this.conn == null && conn != null)
          // rollback only local connection
          conn.rollback();
      } catch (Exception ex3) {
      }

      throw new Exception(ex.getMessage());
    } finally {
      try {
        stmt.close();
      } catch (Exception exx) {
      }
      try {
        if (this.conn == null && conn != null) {
          // close only local connection
          conn.commit();
          conn.close();
        }

      } catch (Exception exx) {
      }
    }
  }
Example #21
0
 /** Test for bug [1371295] SQL Server continues after duplicate key error. */
 public void testPrepStmtBatchDupKey() throws Exception {
   Statement stmt = con.createStatement();
   stmt.execute("create table #testbatch (id int, data varchar(255), PRIMARY KEY (id))");
   PreparedStatement pstmt = con.prepareStatement("INSERT INTO #testbatch VALUES (?, ?)");
   for (int i = 0; i < 5; i++) {
     if (i == 2) {
       pstmt.setInt(1, 1); // Will cause duplicate key batch will continue
     } else {
       pstmt.setInt(1, i);
     }
     pstmt.setString(2, "This is line " + i);
     pstmt.addBatch();
   }
   int x[];
   try {
     x = pstmt.executeBatch();
   } catch (BatchUpdateException e) {
     x = e.getUpdateCounts();
   }
   assertEquals(5, x.length);
   assertEquals(1, x[0]);
   assertEquals(1, x[1]);
   assertEquals(EXECUTE_FAILED, x[2]);
   assertEquals(1, x[3]);
   assertEquals(1, x[4]);
   // Now without errors
   stmt.execute("TRUNCATE TABLE #testbatch");
   for (int i = 0; i < 5; i++) {
     pstmt.setInt(1, i);
     pstmt.setString(2, "This is line " + i);
     pstmt.addBatch();
   }
   x = pstmt.executeBatch();
   assertEquals(5, x.length);
   assertEquals(1, x[0]);
   assertEquals(1, x[1]);
   assertEquals(1, x[2]);
   assertEquals(1, x[3]);
   assertEquals(1, x[4]);
 }
Example #22
0
  static void truncateTable(String strTable) {

    String DBMS = "";
    try {
      DatabaseMetaData metaData = conn.getMetaData();
      DBMS = metaData.getDatabaseProductName().toLowerCase();
    } catch (SQLException e) {
      System.out.println("Problem determining database product name: " + e);
    }
    System.out.println("Truncating '" + strTable + "' ...");
    try {
      if (DBMS.startsWith("db2")) {
        stmt.execute("TRUNCATE TABLE " + strTable + " IMMEDIATE");
      } else {
        stmt.execute("TRUNCATE TABLE " + strTable);
      }
      transCommit();
    } catch (SQLException se) {
      System.out.println(se.getMessage());
      transRollback();
    }
  }
Example #23
0
  public final LentilCursor read(final String sql) {
    final ResultSet results;

    try {
      final Statement stmt = getConnection().createStatement();

      stmt.execute(sql);

      results = stmt.getResultSet();
    } catch (SQLException e) {
      throw new IllegalStateException(e);
    }

    return new LentilCursor(results);
  }
Example #24
0
  public void testTimezoneWithSeconds() throws SQLException {
    if (!TestUtil.haveMinimumServerVersion(con, "8.2")) return;

    Statement stmt = con.createStatement();
    stmt.execute("SET TimeZone = 'Europe/Paris'");
    for (int i = 0; i < PREPARE_THRESHOLD; i++) {
      PreparedStatement ps = con.prepareStatement("SELECT '1920-01-01'::timestamptz");
      ResultSet rs = ps.executeQuery();
      rs.next();
      // select extract(epoch from '1920-01-01'::timestamptz - 'epoch'::timestamptz) * 1000;

      assertEquals(-1577923200000L, rs.getTimestamp(1).getTime());
      ps.close();
    }
  }
Example #25
0
 public void eliminarVenta(String id) {
   Connection cn;
   Statement st;
   ResultSet rs;
   try {
     cn = getConnection();
     st = cn.createStatement();
     String tsql;
     tsql = "delete from ventas where id_venta='" + id + "'";
     st.execute(tsql);
     cn.close();
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
Example #26
0
 /** Test for bug [1371295] SQL Server continues after duplicate key error. */
 public void testBatchDupKey() throws Exception {
   Statement stmt = con.createStatement();
   stmt.execute("create table #testbatch (id int, data varchar(255), PRIMARY KEY (id))");
   for (int i = 0; i < 5; i++) {
     if (i == 2) {
       // This statement will generate an duplicate key error
       stmt.addBatch("INSERT INTO #testbatch VALUES (1, 'This is line " + i + "')");
     } else {
       stmt.addBatch("INSERT INTO #testbatch VALUES (" + i + ", 'This is line " + i + "')");
     }
   }
   int x[];
   try {
     x = stmt.executeBatch();
   } catch (BatchUpdateException e) {
     x = e.getUpdateCounts();
   }
   assertEquals(5, x.length);
   assertEquals(1, x[0]);
   assertEquals(1, x[1]);
   assertEquals(EXECUTE_FAILED, x[2]);
   assertEquals(1, x[3]);
   assertEquals(1, x[4]);
   // Now without errors
   stmt.execute("TRUNCATE TABLE #testbatch");
   for (int i = 0; i < 5; i++) {
     stmt.addBatch("INSERT INTO #testbatch VALUES (" + i + ", 'This is line " + i + "')");
   }
   x = stmt.executeBatch();
   assertEquals(5, x.length);
   assertEquals(1, x[0]);
   assertEquals(1, x[1]);
   assertEquals(1, x[2]);
   assertEquals(1, x[3]);
   assertEquals(1, x[4]);
 }
Example #27
0
  public final int write(final String sql) {
    final int count;

    try {
      final Statement stmt = getConnection().createStatement();
      stmt.execute(sql);

      count = stmt.getUpdateCount();

      stmt.close();
    } catch (SQLException e) {
      throw new IllegalStateException(e);
    }

    return count;
  }
Example #28
0
 public void guardarVenta(VentasBean m) {
   Connection cn;
   Statement st;
   ResultSet rs;
   try {
     cn = getConnection();
     st = cn.createStatement();
     String tsql;
     tsql = "Insert into ventas (id_linea,fecha_venta,descripcion) values('";
     tsql += m.getId_linea() + "','" + m.getFecha() + "','" + m.getDescripcion() + "')";
     st.execute(tsql);
     cn.close();
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
 protected boolean applySecurityToDerby(
     Connection dConn, String sql, ArrayList<SQLException> exList) {
   Log.getLogWriter().info("execute authorization statement in derby");
   Log.getLogWriter().info("security statement is: " + sql);
   try {
     Statement stmt = dConn.createStatement();
     stmt.execute(sql); // execute authorization stmt on derby
   } catch (SQLException se) {
     if (!SQLHelper.checkDerbyException(dConn, se)) { // handles the deadlock of aborting
       Log.getLogWriter().info("detected the deadlock, will try it again");
       return false;
     } else {
       SQLHelper.handleDerbySQLException(se, exList);
     }
   }
   return true;
 }
Example #30
0
 /**
  * test for bug [2827931] that implicitly also tests for bug [1811383]
  *
  * <p>example for statement that produces multiple update counts unexpectedly: IF
  * sessionproperty('ARITHABORT') = 0 SET ARITHABORT ON
  */
 public void testBatchUpdateCounts() throws SQLException {
   Statement statement = con.createStatement();
   statement.execute("CREATE TABLE #BATCHUC (id int)");
   statement.addBatch("insert into #BATCHUC values (1)");
   statement.addBatch("insert into #BATCHUC values (2) insert into #BATCHUC values (3)");
   statement.addBatch(
       "insert into #BATCHUC values (4) insert into #BATCHUC values (5) insert into #BATCHUC values (6)");
   // below: create identifiable update counts to show if/how far they have been shifted due to bug
   // [2827931]
   statement.addBatch("insert into #BATCHUC select * from #BATCHUC");
   statement.addBatch("insert into #BATCHUC select * from #BATCHUC where id=999");
   statement.addBatch("insert into #BATCHUC select * from #BATCHUC where id=999");
   statement.addBatch("insert into #BATCHUC select * from #BATCHUC where id=999");
   statement.addBatch("insert into #BATCHUC select * from #BATCHUC where id=999");
   assertEquals(
       array2String(new int[] {1, 2, 3, 6, 0, 0, 0, 0, 0, 0}),
       array2String(statement.executeBatch()));
   statement.close();
 }