コード例 #1
0
ファイル: QueryDB.java プロジェクト: chenyuguxing/utils
 public void dispose() {
   try {
     stmt.close();
     con.close();
   } catch (SQLException e) {
   }
 }
コード例 #2
0
 private void executeUpdate(Connection conn, String sql) throws SQLException {
   if (conn != null) {
     Statement stmt = conn.createStatement();
     stmt.executeUpdate(sql);
     stmt.close();
   }
 }
コード例 #3
0
ファイル: TestThread.java プロジェクト: openlink/jdbc-bench
 public void executeQuery() throws SQLException {
   log(
       "select account, branch, balance, filler from "
           + m_Driver.getAccountName()
           + " where account < 101\n",
       2);
   Statement stmt = null;
   try {
     stmt = m_conn.createStatement();
     ResultSet set =
         stmt.executeQuery(
             "select account, branch, balance, filler from "
                 + m_Driver.getAccountName()
                 + " where account < 101");
     while (set.next()) {
       set.getInt(1);
       set.getInt(2);
       set.getDouble(3);
       set.getString(4);
     }
     set.close();
   } finally {
     if (stmt != null) stmt.close();
     stmt = null;
   }
 }
コード例 #4
0
  public ExptLocatorTree(Genome g) {
    super();
    try {
      java.sql.Connection c = DatabaseFactory.getConnection(ExptLocator.dbRole);
      int species = g.getSpeciesDBID();
      int genome = g.getDBID();

      Statement s = c.createStatement();
      ResultSet rs = null;

      rs =
          s.executeQuery(
              "select e.name, e.version from experiment e, exptToGenome eg where e.active=1 and "
                  + "e.id=eg.experiment and eg.genome="
                  + genome);
      while (rs.next()) {
        String name = rs.getString(1);
        String version = rs.getString(2);
        ChipChipLocator loc = new ChipChipLocator(g, name, version);
        this.addElement(loc.getTreeAddr(), loc);
      }
      rs.close();

      rs =
          s.executeQuery(
              "select ra.name, ra.version from rosettaanalysis ra, rosettaToGenome rg where "
                  + "ra.id = rg.analysis and ra.active=1 and rg.genome="
                  + genome);
      while (rs.next()) {
        String name = rs.getString(1);
        String version = rs.getString(2);
        MSPLocator msp = new MSPLocator(g, name, version);
        this.addElement(msp.getTreeAddr(), msp);
      }
      rs.close();

      rs =
          s.executeQuery(
              "select ra.name, ra.version from bayesanalysis ra, bayesToGenome rg where "
                  + "ra.id = rg.analysis and ra.active=1 and rg.genome="
                  + genome);
      while (rs.next()) {
        String name2 = rs.getString(1);
        String version2 = rs.getString(2);
        ExptLocator loc2 = new BayesLocator(g, name2, version2);
        addElement(loc2.getTreeAddr(), loc2);
      }
      rs.close();
      s.close();

      DatabaseFactory.freeConnection(c);
    } catch (SQLException se) {
      se.printStackTrace(System.err);
      throw new RuntimeException(se);
    } catch (UnknownRoleException e) {
      e.printStackTrace();
    }
  }
コード例 #5
0
  public void connectItems(String query)
        // PRE:  query must be initialized
        // POST: Updates the list of Items based on the query.
      {
    String driver = "org.apache.derby.jdbc.ClientDriver"; // Driver for DB
    String url = "jdbc:derby://localhost:1527/ShopDataBase"; // Url for DB
    String user = "******"; // Username for db
    String pass = "******"; // Password for db
    Connection myConnection; // Connection obj to db
    Statement stmt; // Statement to execute a result appon
    ResultSet results; // A set containing the returned results
    int rowcount; // Num objects in the resultSet
    int i; // Index for the array

    try { // Try connection to db

      Class.forName(driver).newInstance(); // Create our db driver

      myConnection = DriverManager.getConnection(url, user, pass); // Initalize our connection

      stmt =
          myConnection.createStatement(
              ResultSet.TYPE_SCROLL_INSENSITIVE,
              ResultSet.CONCUR_UPDATABLE); // Create a new statement
      results = stmt.executeQuery(query); // Store the results of our query

      rowcount = 0;
      if (results.last()) // Go to the last result
      {
        rowcount = results.getRow();
        results.beforeFirst();
      }
      itemsArray = new Item[rowcount];

      i = 0;
      while (results.next()) // Itterate through the results set
      {
        itemsArray[i] =
            new Item(
                results.getInt("item_id"),
                results.getString("item_name"),
                results.getString("item_type"),
                results.getInt("price"),
                results.getInt("owner_id"),
                results.getString("item_path")); // Creat new Item
        i++;
      }

      results.close(); // Close the ResultSet
      stmt.close(); // Close the statement
      myConnection.close(); // Close the connection to db

    } catch (Exception e) // Cannot connect to db
    {
      System.err.println(e.toString());
      System.err.println("Error, something went horribly wrong in connectItems!");
    }
  }
コード例 #6
0
 private void close(Statement ps) {
   try {
     if (ps != null) {
       ps.close();
     }
   } catch (SQLException e) {
     LOGGER.error("error during closing:" + e.getMessage(), e);
   }
 }
コード例 #7
0
ファイル: TestThread.java プロジェクト: openlink/jdbc-bench
 public void run() {
   m_nTrans = 0;
   m_nTrans1Sec = 0;
   m_nTrans2Sec = 0;
   m_nTimeSum = 0;
   if (m_nNumRuns <= 0) return;
   Statement stmt = null;
   try {
     stmt = m_conn.createStatement();
     ResultSet set;
     // get branch count
     log("select max(branch) from " + m_Driver.getBranchName() + "\n", 2);
     set = stmt.executeQuery("select max(branch) from " + m_Driver.getBranchName());
     if (set != null && set.next()) {
       m_nMaxBranch = set.getInt(1);
       set.close();
     }
     // get teller count
     log("select max(teller) from " + m_Driver.getTellerName() + "\n", 2);
     set = stmt.executeQuery("select max(teller) from " + m_Driver.getTellerName());
     if (set != null && set.next()) {
       m_nMaxTeller = set.getInt(1);
       set.close();
     }
     // get account count
     log("select max(account) from " + m_Driver.getAccountName() + "\n", 2);
     set = stmt.executeQuery("select max(account) from " + m_Driver.getAccountName());
     if (set != null && set.next()) {
       m_nMaxAccount = set.getInt(1);
       set.close();
     }
   } catch (SQLException e) {
     log("Error getting table limits : " + e.getMessage() + "\n", 0);
   } finally {
     if (stmt != null)
       try {
         stmt.close();
       } catch (SQLException e) {
       }
     stmt = null;
   }
   //		System.out.println("Thread : " + getName() + " Branch :" + m_nMaxBranch + " Teller : " +
   // m_nMaxTeller + " Account : " + m_nMaxAccount);
   if (m_bRunText) runTextTest();
   if (m_bRunPrepared) runPrepareTest();
   if (m_bRunSProc) runProcTest();
   if (m_bCloseConnection) {
     try {
       m_conn.close();
       log("Thread connection closed", 2);
     } catch (SQLException e) {
     }
   }
   if (m_log != null) m_log.taskDone();
 }
コード例 #8
0
  public void updateTables(String updateQuery1, String updateQuery2, String updateQuery3)
        // PRE:  updateQuery1,updateQuery2, updateQuery3 must be initialized
        // POST: Updates the list of Items based on the querys.
      {
    String driver = "org.apache.derby.jdbc.ClientDriver"; // Driver for DB
    String url = "jdbc:derby://localhost:1527/ShopDataBase"; // Url for DB
    String user = "******"; // Username for db
    String pass = "******"; // Password for db
    Connection myConnection; // Connection obj to db
    Statement stmt; // Statement to execute a result appon
    ResultSet results; // A set containing the returned results
    int i; // Index for the array
    try // Try connection to db
    {

      Class.forName(driver).newInstance(); // Create our db driver

      myConnection = DriverManager.getConnection(url, user, pass); // Initalize our connection

      stmt =
          myConnection.createStatement(
              ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
      stmt.executeUpdate(updateQuery1);

      stmt.executeUpdate(updateQuery2);

      stmt.executeUpdate(updateQuery3);

      results = stmt.executeQuery(previous_query); // Call the previous query

      i = 0;
      while (results.next()) // Itterate through the results set
      {
        itemsArray[i] =
            new Item(
                results.getInt("item_id"),
                results.getString("item_name"),
                results.getString("item_type"),
                results.getInt("price"),
                results.getInt("owner_id"),
                results.getString("item_path"));
        i++;
      }
      results.close(); // Close the ResultSet
      stmt.close(); // Close the statement
      myConnection.close(); // Close the connection to db

    } catch (Exception e) // Cannot connect to db
    {
      System.err.println(e.toString());
      System.err.println("Error, something went horribly wrong! in updateTables");
    }
  }
コード例 #9
0
ファイル: TableDeneme.java プロジェクト: herlixjae/tubes1
 public void closeDB() {
   try {
     if (statement != null) {
       statement.close();
     }
     if (db != null) {
       db.close();
     }
   } catch (Exception e) {
     System.out.println("Database could not closed");
     e.printStackTrace();
   }
 } // closeDB sonu
コード例 #10
0
  public void actionPerformed(ActionEvent ae) {
    String str = ae.getActionCommand();
    if (str.equals("Ok")) {
      String str1 = (String) jcmname.getSelectedItem();

      Connection con = null;
      Statement stat = null;

      if (str1.equals("Pulsar")
          || str1.equals("CT 100")
          || str1.equals("Discover DTS-i")
          || str1.equals("Wave DTS-i")) {
        try {
          Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
          con = DriverManager.getConnection("Jdbc:Odbc:showroom");
          System.out.println("Got Connection :" + con);
          stat = con.createStatement();
          ResultSet rs = stat.executeQuery("select * from vehicle");
          System.out.println("chk1");
          while (rs.next()) {
            if (str1.equals(rs.getString(1))) {

              tfcap.setText("" + rs.getInt(2));
              tfeng.setText("" + rs.getInt(3));
              tfbhp.setText("" + rs.getInt(4));
              tfvolt.setText("" + rs.getInt(5));
              tfrpm.setText("" + rs.getInt(6));
              tfweight.setText("" + rs.getInt(7));
              tfgear.setText("" + rs.getInt(8));
            }
          }

          stat.close();
          con.close();

        } catch (Exception ex) {
        }

      } else {
        JOptionPane.showMessageDialog(
            null, "Please Choose Model Name", "Error", JOptionPane.ERROR_MESSAGE);
      }
    }

    if (str.equals("can")) {
      this.dispose();
      // new menu(1);
    }
  }
コード例 #11
0
  /**
   * Fill the table using m_sql
   *
   * @param table table
   */
  private static void tableLoad(MiniTable table) {
    //	log.finest(m_sql + " - " +  m_groupBy);
    String sql =
        MRole.getDefault()
                .addAccessSQL(m_sql.toString(), "tab", MRole.SQL_FULLYQUALIFIED, MRole.SQL_RO)
            + m_groupBy
            + m_orderBy;

    log.finest(sql);
    try {
      Statement stmt = DB.createStatement();
      ResultSet rs = stmt.executeQuery(sql);
      table.loadTable(rs);
      stmt.close();
    } catch (SQLException e) {
      log.log(Level.SEVERE, sql, e);
    }
  } //  tableLoad
コード例 #12
0
ファイル: EchoAWT.java プロジェクト: operationcwal/app
  public void login() {
    String driver = "oracle.jdbc.driver.OracleDriver";
    String url = "jdbc:oracle:thin:@localhost:1521:orcl";
    Connection con = null;
    Statement stmt = null;
    ResultSet rs = null;

    String id, pw, sql;
    try {
      Class.forName(driver);
      con = DriverManager.getConnection(url, "hr", "hr");
      stmt = con.createStatement();
      sql = "select * from chatuser where id = '" + lid.getText() + "'";
      rs = stmt.executeQuery(sql);
      if (rs.next()) {
        pw = rs.getString(2);
        nick = rs.getString(3);
        if (lpw.getText().equals(pw)) {
          jd.setVisible(false);
          setVisible(true);
        } else {
          lpw.setText("일치하지 않습니다.");
        }
      } else {
        lid.setText("일치하지 않습니다.");
      }
    } catch (Exception e1) {
      e1.printStackTrace();
      System.out.println("데이터 베이스 연결 실패!!");
    } finally {
      try {
        if (rs != null) rs.close();
        if (stmt != null) stmt.close();
        if (con != null) con.close();
      } catch (Exception e1) {
        System.out.println(e1.getMessage());
      }
    }
  }
コード例 #13
0
  public void bookRoom() {
    try {
      int code = 0;
      Connection con =
          DriverManager.getConnection(
              "jdbc:mysql://67.20.111.85:3306/jeehtove_caliking?relaxAutoCommit=false",
              "jeehtove_ck",
              "Z_^PBBZT+kcy");
      Statement stmt_insert = con.createStatement();
      Statement stmt_tableRange = con.createStatement();
      Statement stmt_checkrooms = con.createStatement();
      Statement stmt_checkrooms_2 = con.createStatement();

      String insert = null;
      int flag = 0;

      String room_type;
      if (standardRoom.isSelected()) {
        room_type = "Standard";
        code = 1;
      } else if (familyRoom.isSelected()) {
        room_type = "Family";
        code = 2;
      } else {
        room_type = "Suite";
        code = 3;
      }

      // Converting string from checkin and checkout dates so that they can access the correct table
      String currentDate_checkin_getText = checkindateField.getText();
      String currentDate_checkin_rest = currentDate_checkin_getText.substring(5);
      String currentDate_checkin_replace = currentDate_checkin_rest.replace("-", "_");
      String currentDate_checkin_year = currentDate_checkin.substring(0, 4);
      String currentDate_checkin_final =
          currentDate_checkin_year + "_" + currentDate_checkin_replace;

      String currentDate_checkout_getText = checkoutdateField.getText();
      String currentDate_checkout_rest = currentDate_checkout_getText.substring(5);
      String currentDate_checkout_replace = currentDate_checkout_rest.replace("-", "_");
      String currentDate_checkout_year = currentDate_checkout.substring(0, 4);
      String currentDate_checkout_final =
          currentDate_checkout_year + "_" + currentDate_checkout_replace;

      // MySQL Statement to select tables from schema that are in between checkin and checkout range
      String tableRange =
          "SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA='jeehtove_caliking' AND TABLE_NAME BETWEEN 'rooms_"
              + currentDate_checkin_final
              + "' AND 'rooms_"
              + currentDate_checkout_final
              + "';";
      ResultSet tb_Range = stmt_tableRange.executeQuery(tableRange);

      System.out.println(tableRange);
      List tb_range_list = new ArrayList();

      while (tb_Range.next()) {
        String tb_range_date = tb_Range.getString("table_name");
        tb_range_list.add(tb_range_date);
        // String current_table = tb_Range.getString("table_name");
        // System.out.println(tb_range_list.add(tb_Range.getString("table_name")));
      }

      stmt_tableRange.close();

      for (int x = 0; x < tb_range_list.size(); x++) {
        String query_checkrooms =
            "SELECT * FROM "
                + tb_range_list.get(x)
                + " WHERE type = '"
                + code
                + "' AND booked = '0' LIMIT 1;";
        // System.out.println(query_checkrooms);
        ResultSet checkrooms = stmt_checkrooms.executeQuery(query_checkrooms);
        while (checkrooms.next()) {
          String getroomnumber = checkrooms.getString("room");
          insert =
              "INSERT INTO `reservations` VALUES ('"
                  + getroomnumber
                  + "', '"
                  + checkindateField.getText()
                  + "', '"
                  + checkoutdateField.getText()
                  + "',  '"
                  + room_type
                  + "',  '"
                  + nameField.getText()
                  + "');";
          String bookroom =
              "UPDATE `"
                  + tb_range_list.get(x)
                  + "` SET booked = '1' WHERE room = '"
                  + getroomnumber
                  + "';";
          // System.out.println(insert);
          int cr = stmt_checkrooms_2.executeUpdate(bookroom);
          flag = 1;
          System.out.println("Room Booked!");
        }
      }

      if (flag == 1) {
        int rs = stmt_insert.executeUpdate(insert);
      } else {
        System.out.println("All " + room_type + " rooms are booked for the time requested.");
      }

      /*String query_checkrooms = "SELECT * FROM rooms_" + currentDate_checkin_final + " WHERE type = '" + code + "' AND booked = '0';";
      System.out.println(query_checkrooms);
      Statement stmt_checkrooms = con.createStatement();
      ResultSet checkrooms = stmt_checkrooms.executeQuery(query_checkrooms);*/

      /*if (checkrooms.next()){
      		String getroomnumber = checkrooms.getString("room");
      		String insert = "INSERT INTO `reservations` VALUES ('" + getroomnumber + "', '" +  checkindateField.getText() + "', '" +  checkoutdateField.getText() + "',  '" + room_type + "',  '" + nameField.getText() + "');";
      		String bookroom = "UPDATE `rooms_" + currentDate_checkin_final + "` SET booked = '1' WHERE room = '" + getroomnumber + "';";
      //System.out.println(insert);
      	int rs=stmt_insert.executeUpdate(insert);
      	int cr=stmt_checkrooms.executeUpdate(bookroom);
      	con.commit();
      	System.out.println("Room Booked!");
      	}*/

      // else System.out.println("All " + room_type + " rooms are booked for the time requested.");
      System.out.println("Complete.");
    } catch (Exception e) {
      System.out.println(e);
    }
  }
コード例 #14
0
  public void init(boolean force) {
    dbCount = -1;
    String version = null;
    Connection conn = null;
    ResultSet rs = null;
    Statement stmt = null;

    try {
      conn = getConnection();
    } catch (SQLException se) {
      final File dbFile = new File(dbDir + File.separator + dbName + ".data.db");
      final File dbDirectory = new File(dbDir);
      if (dbFile.exists()
          || (se.getErrorCode() == 90048)) { // Cache is corrupt or wrong version, so delete it
        FileUtils.deleteQuietly(dbDirectory);
        if (!dbDirectory.exists()) {
          LOGGER.debug(
              "The cache has been deleted because it was corrupt or had the wrong version");
        } else {
          if (!PMS.isHeadless()) {
            JOptionPane.showMessageDialog(
                (JFrame) (SwingUtilities.getWindowAncestor((Component) PMS.get().getFrame())),
                String.format(Messages.getString("DLNAMediaDatabase.5"), dbDir),
                Messages.getString("Dialog.Error"),
                JOptionPane.ERROR_MESSAGE);
          }
          LOGGER.debug(
              "Damaged cache can't be deleted. Stop the program and delete the folder \""
                  + dbDir
                  + "\" manually");
          configuration.setUseCache(false);
          return;
        }
      } else {
        LOGGER.debug("Cache connection error: " + se.getMessage());
        configuration.setUseCache(false);
        return;
      }
    }

    try {
      conn = getConnection();

      stmt = conn.createStatement();
      rs = stmt.executeQuery("SELECT count(*) FROM FILES");
      if (rs.next()) {
        dbCount = rs.getInt(1);
      }
      rs.close();
      stmt.close();

      stmt = conn.createStatement();
      rs = stmt.executeQuery("SELECT VALUE FROM METADATA WHERE KEY = 'VERSION'");
      if (rs.next()) {
        version = rs.getString(1);
      }
    } catch (SQLException se) {
      if (se.getErrorCode()
          != 42102) { // Don't log exception "Table "FILES" not found" which will be corrected in
        // following step
        LOGGER.error(null, se);
      }
    } finally {
      close(rs);
      close(stmt);
      close(conn);
    }
    boolean force_reinit =
        !PMS.getVersion().equals(version); // here we can force a deletion for a specific version
    if (force || dbCount == -1 || force_reinit) {
      LOGGER.debug("Database will be (re)initialized");
      try {
        conn = getConnection();
        executeUpdate(conn, "DROP TABLE FILES");
        executeUpdate(conn, "DROP TABLE METADATA");
        executeUpdate(conn, "DROP TABLE REGEXP_RULES");
        executeUpdate(conn, "DROP TABLE AUDIOTRACKS");
        executeUpdate(conn, "DROP TABLE SUBTRACKS");
      } catch (SQLException se) {
        if (se.getErrorCode()
            != 42102) { // Don't log exception "Table "FILES" not found" which will be corrected in
          // following step
          LOGGER.error(null, se);
        }
      }
      try {
        StringBuilder sb = new StringBuilder();
        sb.append("CREATE TABLE FILES (");
        sb.append("  ID                INT AUTO_INCREMENT");
        sb.append(", FILENAME          VARCHAR2(1024)       NOT NULL");
        sb.append(", MODIFIED          TIMESTAMP            NOT NULL");
        sb.append(", TYPE              INT");
        sb.append(", DURATION          DOUBLE");
        sb.append(", BITRATE           INT");
        sb.append(", WIDTH             INT");
        sb.append(", HEIGHT            INT");
        sb.append(", SIZE              NUMERIC");
        sb.append(", CODECV            VARCHAR2(").append(SIZE_CODECV).append(")");
        sb.append(", FRAMERATE         VARCHAR2(").append(SIZE_FRAMERATE).append(")");
        sb.append(", ASPECT            VARCHAR2(").append(SIZE_ASPECT).append(")");
        sb.append(", ASPECTRATIOCONTAINER    VARCHAR2(")
            .append(SIZE_ASPECTRATIO_CONTAINER)
            .append(")");
        sb.append(", ASPECTRATIOVIDEOTRACK   VARCHAR2(")
            .append(SIZE_ASPECTRATIO_VIDEOTRACK)
            .append(")");
        sb.append(", REFRAMES          TINYINT");
        sb.append(", AVCLEVEL          VARCHAR2(").append(SIZE_AVC_LEVEL).append(")");
        sb.append(", BITSPERPIXEL      INT");
        sb.append(", THUMB             BINARY");
        sb.append(", CONTAINER         VARCHAR2(").append(SIZE_CONTAINER).append(")");
        sb.append(", MODEL             VARCHAR2(").append(SIZE_MODEL).append(")");
        sb.append(", EXPOSURE          INT");
        sb.append(", ORIENTATION       INT");
        sb.append(", ISO               INT");
        sb.append(", MUXINGMODE        VARCHAR2(").append(SIZE_MUXINGMODE).append(")");
        sb.append(", FRAMERATEMODE     VARCHAR2(").append(SIZE_FRAMERATE_MODE).append(")");
        sb.append(", constraint PK1 primary key (FILENAME, MODIFIED, ID))");
        executeUpdate(conn, sb.toString());
        sb = new StringBuilder();
        sb.append("CREATE TABLE AUDIOTRACKS (");
        sb.append("  FILEID            INT              NOT NULL");
        sb.append(", ID                INT              NOT NULL");
        sb.append(", LANG              VARCHAR2(").append(SIZE_LANG).append(")");
        sb.append(", FLAVOR            VARCHAR2(").append(SIZE_FLAVOR).append(")");
        sb.append(", NRAUDIOCHANNELS   NUMERIC");
        sb.append(", SAMPLEFREQ        VARCHAR2(").append(SIZE_SAMPLEFREQ).append(")");
        sb.append(", CODECA            VARCHAR2(").append(SIZE_CODECA).append(")");
        sb.append(", BITSPERSAMPLE     INT");
        sb.append(", ALBUM             VARCHAR2(").append(SIZE_ALBUM).append(")");
        sb.append(", ARTIST            VARCHAR2(").append(SIZE_ARTIST).append(")");
        sb.append(", SONGNAME          VARCHAR2(").append(SIZE_SONGNAME).append(")");
        sb.append(", GENRE             VARCHAR2(").append(SIZE_GENRE).append(")");
        sb.append(", YEAR              INT");
        sb.append(", TRACK             INT");
        sb.append(", DELAY             INT");
        sb.append(", MUXINGMODE        VARCHAR2(").append(SIZE_MUXINGMODE).append(")");
        sb.append(", BITRATE           INT");
        sb.append(", constraint PKAUDIO primary key (FILEID, ID))");
        executeUpdate(conn, sb.toString());
        sb = new StringBuilder();
        sb.append("CREATE TABLE SUBTRACKS (");
        sb.append("  FILEID            INT              NOT NULL");
        sb.append(", ID                INT              NOT NULL");
        sb.append(", LANG              VARCHAR2(").append(SIZE_LANG).append(")");
        sb.append(", FLAVOR            VARCHAR2(").append(SIZE_FLAVOR).append(")");
        sb.append(", TYPE              INT");
        sb.append(", constraint PKSUB primary key (FILEID, ID))");

        executeUpdate(conn, sb.toString());
        executeUpdate(
            conn,
            "CREATE TABLE METADATA (KEY VARCHAR2(255) NOT NULL, VALUE VARCHAR2(255) NOT NULL)");
        executeUpdate(conn, "INSERT INTO METADATA VALUES ('VERSION', '" + PMS.getVersion() + "')");
        executeUpdate(conn, "CREATE INDEX IDXARTIST on AUDIOTRACKS (ARTIST asc);");
        executeUpdate(conn, "CREATE INDEX IDXALBUM on AUDIOTRACKS (ALBUM asc);");
        executeUpdate(conn, "CREATE INDEX IDXGENRE on AUDIOTRACKS (GENRE asc);");
        executeUpdate(conn, "CREATE INDEX IDXYEAR on AUDIOTRACKS (YEAR asc);");
        executeUpdate(
            conn,
            "CREATE TABLE REGEXP_RULES ( ID VARCHAR2(255) PRIMARY KEY, RULE VARCHAR2(255), ORDR NUMERIC);");
        executeUpdate(conn, "INSERT INTO REGEXP_RULES VALUES ( '###', '(?i)^\\W.+', 0 );");
        executeUpdate(conn, "INSERT INTO REGEXP_RULES VALUES ( '0-9', '(?i)^\\d.+', 1 );");

        // Retrieve the alphabet property value and split it
        String[] chars = Messages.getString("DLNAMediaDatabase.1").split(",");

        for (int i = 0; i < chars.length; i++) {
          // Create regexp rules for characters with a sort order based on the property value
          executeUpdate(
              conn,
              "INSERT INTO REGEXP_RULES VALUES ( '"
                  + chars[i]
                  + "', '(?i)^"
                  + chars[i]
                  + ".+', "
                  + (i + 2)
                  + " );");
        }

        LOGGER.debug("Database initialized");
      } catch (SQLException se) {
        LOGGER.info("Error in table creation: " + se.getMessage());
      } finally {
        close(conn);
      }
    } else {
      LOGGER.debug("Database file count: " + dbCount);
      LOGGER.debug("Database version: " + version);
    }
  }
コード例 #15
0
ファイル: TestThread.java プロジェクト: openlink/jdbc-bench
 void runTextTest() {
   Statement stmt = null;
   try {
     //			System.out.println("Thread :" + getName() + " Text test entered");
     setProgressMinMax(0, m_nNumRuns - 1);
     int nProgressStep = m_nNumRuns / 10 + 1;
     //			System.out.println("Thread :" + getName() + " before commit state");
     boolean m_bTransactionsUsed = m_bTrans && m_conn.getMetaData().supportsTransactions();
     //			System.out.println("Thread :" + getName() + " are transactions used");
     boolean bCurrentAutoCommit = m_conn.getAutoCommit();
     //			System.out.println("Thread :" + getName() + "got currentCommit");
     m_conn.setAutoCommit(!m_bTransactionsUsed);
     //			System.out.println("Thread :" + getName() + " commit state set");
     stmt = m_conn.createStatement();
     int nAccNum, nBranchNum, nTellerNum;
     double dDelta, dBalance;
     log(
         "Starting SQL text benchmark for " + m_nNumRuns + ((m_time > 0) ? " min.\n" : " runs\n"),
         0);
     java.util.Random rand = new java.util.Random(m_nMaxAccount + m_nMaxBranch + m_nMaxTeller);
     for (int nRun = 0; (m_time > 0) ? true : nRun < m_nNumRuns; nRun++) {
       if (m_time > 0) {
         java.util.Date current = new java.util.Date();
         if ((current.getTime() - m_time) > (m_nNumRuns * 60000)) break;
       }
       try {
         nAccNum = (int) (rand.nextFloat() * rand.nextFloat() * (m_nMaxAccount - 1)) + 1;
         nBranchNum = (int) (rand.nextFloat() * (m_nMaxBranch - 1)) + 1;
         nTellerNum = (int) (rand.nextFloat() * (m_nMaxTeller - 1)) + 1;
         dDelta =
             ((double)
                     ((long)
                         ((((int) (rand.nextFloat() * (m_nMaxTeller - 1)) + 1)
                                 * (rand.nextFloat() > 0.5 ? -1 : 1))
                             * 100)))
                 / 100;
         java.util.Date startTime = new java.util.Date();
         log(
             "UPDATE "
                 + m_Driver.getAccountName()
                 + " SET balance = balance + "
                 + dDelta
                 + " WHERE account = "
                 + nAccNum
                 + "\n",
             2);
         stmt.executeUpdate(
             "UPDATE "
                 + m_Driver.getAccountName()
                 + " SET balance = balance + "
                 + dDelta
                 + " WHERE account = "
                 + nAccNum);
         log(
             "SELECT balance FROM "
                 + m_Driver.getAccountName()
                 + " WHERE account = "
                 + nAccNum
                 + "\n",
             2);
         ResultSet balanceSet =
             stmt.executeQuery(
                 "SELECT balance FROM "
                     + m_Driver.getAccountName()
                     + " WHERE account = "
                     + nAccNum);
         balanceSet.next();
         dBalance = balanceSet.getDouble(1);
         balanceSet.close();
         log(
             "UPDATE "
                 + m_Driver.getTellerName()
                 + " SET balance = balance + "
                 + dDelta
                 + " WHERE teller = "
                 + nTellerNum
                 + "\n",
             2);
         stmt.executeUpdate(
             "UPDATE "
                 + m_Driver.getTellerName()
                 + " SET balance = balance + "
                 + dDelta
                 + " WHERE teller = "
                 + nTellerNum);
         log(
             "UPDATE "
                 + m_Driver.getBranchName()
                 + " SET balance = balance + "
                 + dDelta
                 + " WHERE branch = "
                 + nBranchNum
                 + "\n",
             2);
         stmt.executeUpdate(
             "UPDATE "
                 + m_Driver.getBranchName()
                 + " SET balance = balance + "
                 + dDelta
                 + " WHERE branch = "
                 + nBranchNum);
         log(
             "INSERT INTO "
                 + m_Driver.getHistoryName()
                 + " (histid, account, teller, branch, amount, timeoftxn, filler) VALUES ("
                 + nRun
                 + " , "
                 + nAccNum
                 + " , "
                 + nTellerNum
                 + " , "
                 + nBranchNum
                 + " , "
                 + dDelta
                 + " , "
                 + m_nowFunction
                 + " , \'"
                 + BenchPanel.strFiller.substring(0, 21)
                 + "\')\n",
             2);
         stmt.executeUpdate(
             "INSERT INTO "
                 + m_Driver.getHistoryName()
                 + " (histid, account, teller, branch, amount, timeoftxn, filler) VALUES ("
                 + nRun
                 + " , "
                 + nAccNum
                 + " , "
                 + nTellerNum
                 + " , "
                 + nBranchNum
                 + " , "
                 + dDelta
                 + " , "
                 + m_nowFunction
                 + " , \'"
                 + BenchPanel.strFiller.substring(0, 21)
                 + "\')");
         if (m_bQuery) executeQuery();
         //					System.out.println("Done query");
         if (m_bTransactionsUsed) m_conn.commit();
         java.util.Date endTime = new java.util.Date();
         //					System.out.println("Done");
         m_nTrans += 1;
         long diff = endTime.getTime() - startTime.getTime();
         if (diff < 1000) m_nTrans1Sec += 1;
         else if (diff < 2000) m_nTrans2Sec += 1;
         m_nTimeSum += ((double) diff) / 1000;
       } catch (SQLException e1) {
         // System.err.println(e1.getMessage());
         // e1.printStackTrace();
         break;
       }
       if (nRun % nProgressStep == 0) setProgressValue(nRun);
       // yield();
     }
     setProgressValue(m_nNumRuns - 1);
     m_conn.setAutoCommit(bCurrentAutoCommit);
   } catch (SQLException e) {
     // e.printStackTrace();
     // JOptionPane.showMessageDialog(null, e.getMessage(), "SQL Error in Text test",
     // JOptionPane.ERROR_MESSAGE);
     log("SQLError in text test : " + e.getMessage(), 0);
   } finally {
     if (stmt != null)
       try {
         stmt.close();
       } catch (SQLException e) {
       }
   }
 }