private void testIndexNotRebuilt() throws SQLException {
   if (config.memory) {
     return;
   }
   deleteDb("databaseEventListener");
   String url = getURL("databaseEventListener", true);
   String user = getUser(), password = getPassword();
   Properties p = new Properties();
   p.setProperty("user", user);
   p.setProperty("password", password);
   Connection conn = DriverManager.getConnection(url, p);
   Statement stat = conn.createStatement();
   // the old.id index head is at position 0
   stat.execute("create table old(id identity) as select 1");
   // the test.id index head is at position 1
   stat.execute("create table test(id identity) as select 1");
   conn.close();
   conn = DriverManager.getConnection(url, p);
   stat = conn.createStatement();
   // free up space at position 0
   stat.execute("drop table old");
   // truncate, relocating to position 0
   stat.execute("truncate table test");
   stat.execute("insert into test select 1");
   conn.close();
   calledCreateIndex = false;
   p.put("DATABASE_EVENT_LISTENER", getClass().getName());
   conn = org.h2.Driver.load().connect(url, p);
   conn.close();
   assertTrue(!calledCreateIndex);
 }
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    try {
      PrintWriter pw = response.getWriter();
      pw.write(" <html>  <body>");

      Class.forName("com.mysql.jdbc.Driver");

      Connection con =
          DriverManager.getConnection("jdbc:mysql://localhost:3307/project", "root", "root");
      Connection con2 =
          DriverManager.getConnection("jdbc:mysql://localhost:3307/project", "root", "root");

      Statement stm = con.createStatement();
      Statement stm2 = con2.createStatement();

      ResultSet rs;
      ResultSet rs2;

      rs = stm.executeQuery("select * from rc");

      while (rs.next()) {
        if (rs.getString(3) != null) {
          pw.write("<br><br>Username:"******"</body>	</html>");

    } catch (Exception e) {

    }
  }
  private void btnDeleteActionPerformed(
      java.awt.event.ActionEvent evt) { // GEN-FIRST:event_btnDeleteActionPerformed
    Connection dbConnection = null;
    PreparedStatement pstatement = null;
    String sql;
    try {
      DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
      dbConnection =
          DriverManager.getConnection(
              "jdbc:oracle:thin:@deltahiti31202:1521:XE", "Kaushal", "thullu");
      sql = "DELETE FROM EMPLOYEES WHERE EMPLOYEE_ID=?";
      pstatement = dbConnection.prepareStatement(sql);
      pstatement.setInt(1, Integer.parseInt(txtEmployeeID.getText()));
      pstatement.executeUpdate();
    } catch (SQLException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } finally {
      try {
        if (dbConnection != null && !dbConnection.isClosed()) {
          dbConnection.close();
        }
        if (pstatement != null) {
          pstatement.close();
        }

      } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
  } // GEN-LAST:event_btnDeleteActionPerformed
  @Test
  public void testUpsertDateValues() throws Exception {
    long ts = nextTimestamp();
    Date now = new Date(System.currentTimeMillis());
    ensureTableCreated(getUrl(), TestUtil.PTSDB_NAME, null, ts - 2);
    Properties props = new Properties();
    props.setProperty(
        PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 1)); // Execute at timestamp 1
    Connection conn = DriverManager.getConnection(PHOENIX_JDBC_URL, props);
    String dateString = "1999-01-01 02:00:00";
    PreparedStatement upsertStmt =
        conn.prepareStatement(
            "upsert into ptsdb(inst,host,date) values('aaa','bbb',to_date('" + dateString + "'))");
    int rowsInserted = upsertStmt.executeUpdate();
    assertEquals(1, rowsInserted);
    upsertStmt =
        conn.prepareStatement(
            "upsert into ptsdb(inst,host,date) values('ccc','ddd',current_date())");
    rowsInserted = upsertStmt.executeUpdate();
    assertEquals(1, rowsInserted);
    conn.commit();

    props.setProperty(
        PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 2)); // Execute at timestamp 1
    conn = DriverManager.getConnection(PHOENIX_JDBC_URL, props);
    String select = "SELECT date,current_date() FROM ptsdb";
    ResultSet rs = conn.createStatement().executeQuery(select);
    Date then = new Date(System.currentTimeMillis());
    assertTrue(rs.next());
    Date date = DateUtil.parseDate(dateString);
    assertEquals(date, rs.getDate(1));
    assertTrue(rs.next());
    assertTrue(rs.getDate(1).after(now) && rs.getDate(1).before(then));
    assertFalse(rs.next());
  }
Exemple #5
0
  public static void main(String[] args) {
    Connection con = null;
    Statement stmt = null;

    try {
      DriverManager.registerDriver(new com.mysql.jdbc.Driver());

      con = DriverManager.getConnection("jdbc:mysql://localhost:3306/java76db", "java76", "1111");

      stmt = con.createStatement();

      // update 실행
      stmt.executeUpdate("update board set title='okok', content='okokxxx' where bno=9");

      System.out.println("변경 성공!");

    } catch (Exception e) {
      e.printStackTrace();

    } finally {
      try {
        stmt.close();
      } catch (Exception e) {
      }
      try {
        con.close();
      } catch (Exception e) {
      }
    }
  }
Exemple #6
0
  public static void CloseDbConnection(Connection conn) {
    try { // shut down the database
      conn.close();
      System.out.println("Closed connection");

      /* In embedded mode, an application should shut down Derby.
      Shutdown throws the XJ015 exception to confirm success. */
      boolean gotSQLExc = false;
      try {
        DriverManager.getConnection("jdbc:derby:;shutdown=true");
        DriverManager.getConnection("exit");
      } catch (SQLException se) {
        if (se.getSQLState().equals("XJ015")) {
          gotSQLExc = true;
        }
      }
      if (!gotSQLExc) {
        System.out.println("Database did not shut down normally");
      } else {
        System.out.println("Database shut down normally");
      }

      // force garbage collection to unload the EmbeddedDriver
      //  so Derby can be restarted
      System.gc();
    } catch (Throwable e) {
      System.out.println(e);
      ;
      System.exit(1);
    }
  }
  public Connection connect(String url, Properties info) throws SQLException {
    if (acceptsURL(url)) {
      String fileName = getFileNameFromUrl(url);
      try {
        Configuration configuration = configLoader.load(fileName);

        List<String> drivers = configuration.getDrivers();
        for (String classname : drivers) {
          Class<? extends Driver> driverClass = (Class<? extends Driver>) Class.forName(classname);
          Driver driver = driverClass.newInstance();
          java.sql.DriverManager.registerDriver(driver);
          logger.debug("Registering driver " + classname);
        }

        List<ConnectionInfo> connections = configuration.getConnections();

        ConnectionsHolder connectionsHolder = new ConnectionsHolder();
        for (ConnectionInfo connectionInfo : connections) {
          Properties properties = new Properties(info);
          properties.setProperty("user", connectionInfo.getUser());
          properties.setProperty("password", connectionInfo.getPassword());

          Connection connection = DriverManager.getConnection(connectionInfo.getUrl(), properties);
          connectionsHolder.add(connectionInfo.getName(), connection);
        }
        return new ShardsConnection(connectionsHolder, configuration);
      } catch (Exception e) {
        throw new SQLException("Cannot load configuration file", e);
      }
    } else {
      return null;
    }
  }
  public MPJdbcClient(String uri, MPJdbcClientOptions clientOptions, MPJdbcFormatPlugin plugin) {
    try {
      Class.forName(clientOptions.getDriver()).newInstance();
      this.clientOptions = clientOptions;

      String user = this.clientOptions.getUser();
      String passwd = this.clientOptions.getPassword();
      this.plugin = plugin;
      this.uri = uri;

      if (user == null || user.length() == 0 || passwd.length() == 0) {
        logger.info("username, password assumed to be in the uri");
        this.conn = DriverManager.getConnection(uri);
      } else {
        this.conn = DriverManager.getConnection(uri, user, passwd);
      }
      this.metadata = this.conn.getMetaData();
      this.plugName = plugin.getName();
    } catch (InstantiationException e) {
      // TODO Auto-generated catch block
      new DrillRuntimeException(e);
    } catch (IllegalAccessException e) {
      // TODO Auto-generated catch block
      new DrillRuntimeException(e);
    } catch (ClassNotFoundException e) {
      // TODO Auto-generated catch block
      new DrillRuntimeException(e);
    } catch (SQLException e) {
      new DrillRuntimeException(e);
    }
  }
Exemple #9
0
 private static Connection createConnection() {
   try {
     if (Settings.globals.getBoolean("Database.UseMySQL", false)) {
       Class.forName("com.mysql.jdbc.Driver");
       Connection ret =
           DriverManager.getConnection(
               Settings.globals.getString("Database.MySQLConn", ""),
               Settings.globals.getString("Database.MySQLUsername", ""),
               Settings.globals.getString("Database.MySQLPassword", ""));
       ret.setAutoCommit(false);
       return ret;
     } else {
       Class.forName("org.sqlite.JDBC");
       Connection ret =
           DriverManager.getConnection(
               "jdbc:sqlite:plugins"
                   + File.separator
                   + "MonsterHunt"
                   + File.separator
                   + "MonsterHunt.sqlite");
       ret.setAutoCommit(false);
       return ret;
     }
   } catch (ClassNotFoundException e) {
     e.printStackTrace();
     return null;
   } catch (SQLException e) {
     e.printStackTrace();
     return null;
   }
 }
  @BeforeTest
  public void createConnection() throws Exception {
    JdbcStringBasedStoreConfigurationBuilder storeBuilder =
        TestCacheManagerFactory.getDefaultCacheConfiguration(false)
            .persistence()
            .addStore(JdbcStringBasedStoreConfigurationBuilder.class);
    UnitTestDatabaseManager.buildTableManipulation(storeBuilder.table(), false);
    factoryConfiguration =
        UnitTestDatabaseManager.configureUniqueConnectionFactory(storeBuilder).create();
    tableManipulation = new TableManipulation(storeBuilder.table().create());

    if (factoryConfiguration instanceof SimpleConnectionFactoryConfiguration) {
      SimpleConnectionFactoryConfiguration simpleConfiguration =
          (SimpleConnectionFactoryConfiguration) factoryConfiguration;
      connection =
          DriverManager.getConnection(
              simpleConfiguration.connectionUrl(),
              simpleConfiguration.username(),
              simpleConfiguration.password());

    } else if (factoryConfiguration instanceof PooledConnectionFactoryConfiguration) {
      PooledConnectionFactoryConfiguration pooledConfiguration =
          (PooledConnectionFactoryConfiguration) factoryConfiguration;
      connection =
          DriverManager.getConnection(
              pooledConfiguration.connectionUrl(),
              pooledConfiguration.username(),
              pooledConfiguration.password());
    }
    tableManipulation.setCacheName("aName");
  }
Exemple #11
0
  private Connection getConnection() {
    Connection conn = null;
    Properties connProp = new Properties();
    connProp.put("user", this.username);
    connProp.put("password", this.password);

    if (this.dbms.equals("mysql")) {
      try {
        conn =
            DriverManager.getConnection(
                "jdbc:" + this.dbms + "://" + this.hostname + ":" + this.port + "/", connProp);
      } catch (SQLException e) {
        System.out.println("Invalid connection");
      }
    } else if (this.dbms.equals("derby")) {
      try {
        conn =
            DriverManager.getConnection(
                "jdbc:" + this.dbms + ":" + this.database + ";create=true", connProp);
      } catch (SQLException e) {
        System.out.println("Invalid connection");
      }
    }
    return conn;
  }
  private void reconnect() throws SQLException {
    if (driverFailed) {
      return;
    }

    if (connection != null) {
      try {
        connection.close();
      } catch (SQLException e) {
        log.log(Level.WARNING, e.getMessage(), e);
      }
    }

    logInsert = null;
    logInsertAttribute = null;
    connection =
        username != null && !username.trim().isEmpty()
            ? DriverManager.getConnection(
                url, username.trim(), password != null ? password.trim() : null)
            : DriverManager.getConnection(url);

    logInsert = connection.prepareStatement(logInsertQuery, Statement.RETURN_GENERATED_KEYS);

    if (logInsertAttributeQuery != null && !logInsertAttributeQuery.trim().equals("")) {
      logInsertAttribute = connection.prepareStatement(logInsertAttributeQuery);
    }

    // Disable autocommit
    connection.setAutoCommit(false);
  }
 /**
  * Print an Exception stack trace to the log.
  *
  * @param e the exception to log
  */
 public static void logException(Exception e) {
   if (log != null) {
     e.printStackTrace(log);
   } else if (DriverManager.getLogWriter() != null) {
     e.printStackTrace(DriverManager.getLogWriter());
   }
 }
  /**
   * Verbindet dieses Object mit der Datenbank und gibt <code>true</code> zurück, wenn die
   * Verbindung erfolgreich aufgebaut wurde, sonst ein <code>false</code>.
   *
   * @return <code>true</code> wenn die Verbindung erfolgreich aufgebaut wurde, sonst <code>false
   *     </code>.
   */
  public boolean connect() {

    boolean isConnected = true;

    Driver embeddedDriver = new org.apache.derby.jdbc.EmbeddedDriver();

    try {

      DriverManager.registerDriver(embeddedDriver);
    } catch (SQLException ex) {

      System.out.println(ex.getMessage());
    }

    try {

      connection = DriverManager.getConnection(jdbcURL);
    } catch (SQLException ex) {

      isConnected = false;
      System.out.println("Connection could not be established.");
    }

    return isConnected;
  }
Exemple #15
0
    public void actionPerformed(ActionEvent e) {
      try {
        String name = JOptionPane.showInputDialog("Enter the UserId:");
        String name1 = JOptionPane.showInputDialog("Enter the Password:"******"Enter the MobileNo:");
        // int name2=Integer.parseInt(name22);
        String name3 = JOptionPane.showInputDialog("Enter the DOB(dd/mm/yyyy):");
        DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
        Connection con =
            DriverManager.getConnection(
                "jdbc:oracle:thin:@localhost:1521:xe", "system", "9696030257");
        Statement st = con.createStatement();
        st.executeUpdate(
            "insert into database values('"
                + name
                + "','"
                + name1
                + "','"
                + name2
                + "','"
                + name3
                + "')");
        st.executeUpdate("commit");
        JOptionPane.showMessageDialog(
            null,
            "Hi !! Welcome in Our Database.Your userId is  < "
                + name
                + " > And Password is < ******* >");

      } catch (Exception ex) {
        System.out.print(ex);
        JOptionPane.showMessageDialog(null, "Please Fill All Entry OR choose another UsetId.");
      }
    }
 private void paticionDeDatos() throws SQLException {
   try {
     System.out.println(QInsertaDatabase);
     System.out.println(QOption1);
     System.out.println(QOption2);
     BufferedReader leerEntrada = new BufferedReader(new InputStreamReader(System.in));
     String salida = leerEntrada.readLine();
     switch (salida) {
       case "1":
         conexion = DriverManager.getConnection(DBaseServer, "ilsaserver", "platano");
         DBSelected = DBaseServer;
         break;
       case "2":
         DBSelected = DBaseLocal;
         conexion = DriverManager.getConnection(DBaseLocal, "ilsaserver", "platano");
         break;
       default:
         System.err.println("Error Procesando Seleccion, pruebe de nuevo");
         paticionDeDatos();
         break;
     }
   } catch (IOException e) {
     System.err.println("Error Procesando Seleccion, pruebe de nuevo");
     paticionDeDatos();
   }
 }
Exemple #17
0
  /*
   * (non-Javadoc)
   *
   * @see
   * com.absir.bean.config.IBeanFactoryStopping#stopping(com.absir.bean.basis
   * .BeanFactory)
   */
  @Override
  public void stopping(BeanFactory beanFactory) {
    LOGGER.info("stop begin");
    stopConnectionProvider(sessionFactory);
    for (SessionFactoryImpl sessionFactory : sessionFactoryMapName.keySet()) {
      stopConnectionProvider(sessionFactory);
    }

    Environment.setStarted(false);
    if (!driverShared) {
      Enumeration<Driver> enumeration = DriverManager.getDrivers();
      while (enumeration.hasMoreElements()) {
        Driver driver = enumeration.nextElement();
        try {
          DriverManager.deregisterDriver(driver);

        } catch (Exception e) {
          LOGGER.error("deregisterDriver " + driver, e);
        }
      }
    }

    if (driverStoppingCommand != null) {
      for (String stoppingCommand : driverStoppingCommand) {
        KernelClass.invokeCommandString(stoppingCommand);
      }

      driverStoppingCommand = null;
    }

    LOGGER.info("stop complete");
  }
Exemple #18
0
  public void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException {

    Object obj = JSONValue.parse(req.getReader());

    JSONArray array = (JSONArray) obj;

    JSONObject requestParams = (JSONObject) array.get(0);
    int radioID =
        requestParams.get("radio") == null
            ? 0
            : Integer.parseInt((String) requestParams.get("radio"));
    long userID = requestParams.get("userId") == null ? 0 : (long) requestParams.get("userId");
    @SuppressWarnings("unchecked")
    ArrayList<String> checkboxList = (ArrayList<String>) requestParams.get("checkboxes");

    String query = queryBuilder(radioID, userID, checkboxList);

    PrintWriter out = res.getWriter();
    res.setContentType("text/html; charset=UTF-8");
    String endJson = "";
    if (query != null) {
      try {
        java.sql.DriverManager.registerDriver(new com.google.appengine.api.rdbms.AppEngineDriver());
        c = java.sql.DriverManager.getConnection("jdbc:google:rdbms://valiminee:evalimine2/db");
        if (c != null) {
          java.sql.ResultSet rs = c.createStatement().executeQuery(query);
          endJson = ResultSetConverter.convert(rs).toString();
        }
      } catch (java.sql.SQLException | JSONException e) {
        e.printStackTrace();
      }
    }
    out.print(endJson);
  }
Exemple #19
0
  /**
   * * Test SSL client connection to SSL server
   *
   * @throws Exception
   */
  @Test
  public void testSSLConnectionWithProperty() throws Exception {
    setSslConfOverlay(confOverlay);
    // Test in binary mode
    setBinaryConfOverlay(confOverlay);
    // Start HS2 with SSL
    miniHS2.start(confOverlay);

    System.setProperty(JAVA_TRUST_STORE_PROP, dataFileDir + File.separator + TRUST_STORE_NAME);
    System.setProperty(JAVA_TRUST_STORE_PASS_PROP, KEY_STORE_PASSWORD);
    // make SSL connection
    hs2Conn =
        DriverManager.getConnection(
            miniHS2.getJdbcURL() + ";ssl=true", System.getProperty("user.name"), "bar");
    hs2Conn.close();
    miniHS2.stop();

    // Test in http mode
    setHttpConfOverlay(confOverlay);
    miniHS2.start(confOverlay);
    // make SSL connection
    hs2Conn =
        DriverManager.getConnection(
            miniHS2.getJdbcURL("default", SSL_CONN_PARAMS), System.getProperty("user.name"), "bar");
    hs2Conn.close();
  }
  /**
   * Context destroyed.
   *
   * @param sce the sce
   */
  @Override
  public void contextDestroyed(ServletContextEvent sce) {

    ConnectionPool connectionPool;
    connectionPool = ConnectionPool.getInstance();
    connectionPool.shutDown();

    //  ShutDown Abandoned Connection  :  memory leaks after Tomcat stops
    try {
      AbandonedConnectionCleanupThread.shutdown();
      LOG.info("Abandoned connection shut down!");
    } catch (InterruptedException e) {
      LOG.warn("SEVERE problem cleaning up: " + e.getMessage());
      e.printStackTrace();
    }
    //  This manually deregisters JDBC driver, which prevents Tomcat  from complaining about memory
    // leaks this class
    Enumeration<Driver> drivers = DriverManager.getDrivers();
    while (drivers.hasMoreElements()) {
      Driver driver = drivers.nextElement();
      try {
        DriverManager.deregisterDriver(driver);
        LOG.info(String.format("deregistering jdbc driver: %s ", driver));
      } catch (SQLException e) {
        LOG.error(String.format("Error deregistering driver: %s ", driver), e);
      }
    }
  }
  @Test
  public void testUpsertValuesWithDate() throws Exception {
    long ts = nextTimestamp();
    Properties props = new Properties();
    props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts));
    Connection conn = DriverManager.getConnection(getUrl(), props);
    conn.createStatement()
        .execute("create table UpsertDateTest (k VARCHAR not null primary key,date DATE)");
    conn.close();

    props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 5));
    conn = DriverManager.getConnection(getUrl(), props);
    conn.createStatement()
        .execute("upsert into UpsertDateTest values ('a',to_date('2013-06-08 00:00:00'))");
    conn.commit();
    conn.close();

    props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 10));
    conn = DriverManager.getConnection(getUrl(), props);
    ResultSet rs =
        conn.createStatement().executeQuery("select k,to_char(date) from UpsertDateTest");
    assertTrue(rs.next());
    assertEquals("a", rs.getString(1));
    assertEquals("2013-06-08 00:00:00", rs.getString(2));
  }
 static Connection connectToDb(String uname, String pword) throws SQLException {
   DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
   Connection con =
       DriverManager.getConnection(
           "jdbc:oracle:thin:hr/[email protected]:1521:orcl", uname.trim(), pword.trim());
   return con;
 }
  @Test
  public void testUpsertValuesWithExpression() throws Exception {
    long ts = nextTimestamp();
    ensureTableCreated(getUrl(), "IntKeyTest", null, ts - 2);
    Properties props = new Properties();
    props.setProperty(
        PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 1)); // Execute at timestamp 1
    Connection conn = DriverManager.getConnection(PHOENIX_JDBC_URL, props);
    String upsert = "UPSERT INTO IntKeyTest VALUES(-1)";
    PreparedStatement upsertStmt = conn.prepareStatement(upsert);
    int rowsInserted = upsertStmt.executeUpdate();
    assertEquals(1, rowsInserted);
    upsert = "UPSERT INTO IntKeyTest VALUES(1+2)";
    upsertStmt = conn.prepareStatement(upsert);
    rowsInserted = upsertStmt.executeUpdate();
    assertEquals(1, rowsInserted);
    conn.commit();
    conn.close();

    props.setProperty(
        PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 2)); // Execute at timestamp 1
    conn = DriverManager.getConnection(PHOENIX_JDBC_URL, props);
    String select = "SELECT i FROM IntKeyTest";
    ResultSet rs = conn.createStatement().executeQuery(select);
    assertTrue(rs.next());
    assertEquals(-1, rs.getInt(1));
    assertTrue(rs.next());
    assertEquals(3, rs.getInt(1));
    assertFalse(rs.next());
  }
Exemple #24
0
  public DBStorage(String url, String dbName, String username, String password)
      throws SQLException {
    this.username = username;
    this.password = password;
    this.DBName = dbName;
    this.DB_URL = url;
    this.DBName = dbName;

    try {
      Class.forName("org.gjt.mm.mysql.Driver");
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
    }

    Connection tmpConnection = DriverManager.getConnection(DB_URL, username, password);

    Statement stmt = tmpConnection.createStatement();
    stmt.executeUpdate("CREATE DATABASE IF NOT EXISTS " + dbName);
    stmt.close();
    tmpConnection.close();

    this.connection = DriverManager.getConnection(DB_URL + dbName, username, password);

    System.out.println("Database created successfully...");
  }
  @Test
  public void testAllowDropParentTableWithCascadeAndSingleTenantTable() throws Exception {
    long ts = nextTimestamp();
    Properties props = new Properties();
    props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts));
    Connection conn = DriverManager.getConnection(getUrl(), props);
    Connection connTenant = null;

    try {
      // Drop Parent Table
      conn.createStatement().executeUpdate("DROP TABLE " + PARENT_TABLE_NAME + " CASCADE");
      conn.close();

      props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 10));
      connTenant = DriverManager.getConnection(PHOENIX_JDBC_TENANT_SPECIFIC_URL, props);

      validateTenantViewIsDropped(conn);
    } finally {
      if (conn != null) {
        conn.close();
      }
      if (connTenant != null) {
        connTenant.close();
      }
    }
  }
Exemple #26
0
 @Test
 public void testCreateMultiTenantTable() throws Exception {
   long ts = nextTimestamp();
   Properties props = new Properties();
   props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts));
   Connection conn = DriverManager.getConnection(getUrl(), props);
   String ddl =
       "CREATE TABLE m_multi_tenant_test(                TenantId UNSIGNED_INT NOT NULL ,\n"
           + "                Id UNSIGNED_INT NOT NULL ,\n"
           + "                val VARCHAR ,\n"
           + "                CONSTRAINT pk PRIMARY KEY(TenantId, Id) \n"
           + "                ) MULTI_TENANT=true";
   conn.createStatement().execute(ddl);
   props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 10));
   conn = DriverManager.getConnection(getUrl(), props);
   try {
     conn.createStatement().execute(ddl);
     fail();
   } catch (TableAlreadyExistsException e) {
     // expected
   }
   props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 20));
   conn = DriverManager.getConnection(getUrl(), props);
   conn.createStatement().execute("DROP TABLE m_multi_tenant_test");
 }
  public void contextDestroyed(ServletContextEvent sce) {

    // This manually deregisters JDBC driver, which prevents Tomcat 7 from complaining about memory
    // leaks wrto this class
    Enumeration<Driver> drivers = DriverManager.getDrivers();
    while (drivers.hasMoreElements()) {
      Driver driver = drivers.nextElement();
      try {
        DriverManager.deregisterDriver(driver);
        LOG.info(String.format("deregistering jdbc driver: %s", driver));
      } catch (SQLException e) {
        LOG.warn(String.format("Error deregistering driver %s", driver), e);
      }
    }

    // Try to kill the TOMCAT abandoned connection clean up thread
    // to prevent it from holding the whole context in memory causing
    // a leak

    Set<Thread> threadSet = Thread.getAllStackTraces().keySet();
    Thread[] threadArray = threadSet.toArray(new Thread[threadSet.size()]);

    for (Thread t : threadArray) {
      if (t.getName().contains("Abandoned connection cleanup thread")) {
        synchronized (t) {
          t.stop(); // don't complain, it works
        }
      }
    }
  }
  public Connection openConnect() {

    try {
      Class.forName("oracle.jdbc.driver.OracleDriver");
      // load the oracle driver...needs to be in classes folder in jre folder
    } catch (ClassNotFoundException e) {
      System.out.println(" Can't find class oracle.jdbc.driver.OracleDriver");
      System.exit(1);
    }

    try {

      conn =
          DriverManager.getConnection(
              "jdbc:oracle:thin:@studentoracle.students.ittralee.ie:1521/orcl",
              "t00171168",
              "p9udna7n");

      return conn;
    } catch (Exception w) {
      try {
        conn =
            DriverManager.getConnection(
                "jdbc:oracle:thin:@localhost:1521/orcl.168.5.67", "hr", "hr");

        return conn;
      } catch (SQLException ex) {
        JOptionPane.showMessageDialog(null, "Unable to connect to database");
      }
    }
    return conn;
  }
  private void btnInsertActionPerformed(
      java.awt.event.ActionEvent evt) { // GEN-FIRST:event_btnInsertActionPerformed
    Connection dbConnection = null;
    PreparedStatement pstatement = null;
    String sql;
    try {
      DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
      dbConnection =
          DriverManager.getConnection(
              "jdbc:oracle:thin:@deltahiti31202:1521:XE", "Kaushal", "thullu");
      sql = "INSERT INTO EMPLOYEES(EMPLOYEE_ID,FIRST_NAME,LAST_NAME,SALARY) VALUES (?,?,?,?)";
      pstatement = dbConnection.prepareStatement(sql);
      pstatement.setInt(1, Integer.parseInt(txtEmployeeID.getText()));
      pstatement.setString(2, txtFirstName.getText());
      pstatement.setString(3, txtLastName.getText());
      pstatement.setDouble(4, Double.parseDouble(txtSalary.getText()));
      pstatement.executeUpdate();
    } catch (SQLException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } finally {
      try {
        if (dbConnection != null && !dbConnection.isClosed()) {
          dbConnection.close();
        }
        if (pstatement != null) {
          pstatement.close();
        }

      } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
  } // GEN-LAST:event_btnInsertActionPerformed
Exemple #30
0
  static {
    String title = ING_TRACE_NAME + "-Driver";

    /*
     ** Initialize Ingres driver tracing.
     */
    IngConfig.setDriverVers(driverMajorVersion, driverMinorVersion, driverPatchVersion);
    TraceLog traceLog = IngTrace.getTraceLog();

    /*
     ** Create IngresDriver object and register with DriverManager.
     */
    try {
      DriverManager.registerDriver(new IngresDriver());
      DriverManager.println(
          ING_DRIVER_NAME
              + ": Version "
              + driverMajorVersion
              + "."
              + driverMinorVersion
              + "."
              + driverPatchVersion
              + " ("
              + driverJdbcVersion
              + ")");
      DriverManager.println(driverVendor);
      traceLog.write(title + ": registered");
    } catch (Exception ex) {
      DriverManager.println(ING_DRIVER_NAME + ": registration failed!");
      traceLog.write(title + ": registration failed!");
    }
  } // <class initializer>