Esempio n. 1
2
  // Takes and image_id, pulls in the image from cache, and goes about
  // encoding it to put it into the database in a transaction.  The last
  // query in the transaction records the image having been stored.
  protected void storeImage(int image_id) throws Exception {
    PhotoImage p = new PhotoImage(image_id);
    SpyDB pdb = getDB();
    Connection db = null;
    Statement st = null;
    Vector v = p.getImage();
    System.err.println(
        "Storer: Got image for " + image_id + " " + v.size() + " lines of data to store.");
    try {
      int i = 0, n = 0;
      db = pdb.getConn();
      db.setAutoCommit(false);
      st = db.createStatement();
      BASE64Encoder base64 = new BASE64Encoder();
      String data = "";

      for (; i < v.size(); i++) {
        String tmp = base64.encodeBuffer((byte[]) v.elementAt(i));
        tmp = tmp.trim();

        if (data.length() < 2048) {
          data += tmp + "\n";
        } else {
          storeQuery(image_id, n, st, data);
          data = tmp;
          n++;
        }
      }
      // OK, this is sick, but another one right now for the spare.
      if (data.length() > 0) {
        System.err.println("Storer:  Storing spare.");
        storeQuery(image_id, n, st, data);
        n++;
      }
      System.err.println("Storer:  Stored " + n + " lines of data for " + image_id + ".");
      st.executeUpdate(
          "update upload_log set stored=datetime(now())\n" + "\twhere photo_id = " + image_id);
      db.commit();
      // Go ahead and generate a thumbnail.
      p.getThumbnail();
    } catch (Exception e) {
      // If anything happens, roll it back.
      if (st != null) {
        try {
          db.rollback();
        } catch (Exception e3) {
          // Nothing
        }
      }
    } finally {
      if (db != null) {
        try {
          db.setAutoCommit(true);
        } catch (Exception e) {
          System.err.println("Error:  " + e);
        }
      }
      pdb.freeDBConn();
    }
  }
Esempio n. 2
1
 static void attributeMean() {
   try {
     Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
     con = DriverManager.getConnection("jdbc:odbc:jbdb", "system", "tiger");
     Statement meanQuery = con.createStatement();
     ResultSet mean = meanQuery.executeQuery("select AVG(sal) from employ where sal IS NOT NULL");
     if (mean.next()) {
       fill = con.createStatement();
       fill.executeUpdate("UPDATE employ set sal = COALESCE(sal," + mean.getInt(1) + ")");
     }
     /*fill = con.createStatement();
     fill.executeUpdate("UPDATE employ set sal = COALESCE(sal,AVG(sal))");*/
     st = con.createStatement();
     rs = st.executeQuery("select * from employ");
     System.out.println("Sno\tName\tSalary\tGPF\tGrade");
     while (rs.next()) {
       System.out.println(
           ">>"
               + rs.getString(1)
               + "\t"
               + rs.getString(2)
               + "\t"
               + rs.getString(3)
               + "\t"
               + rs.getString(4)
               + "\t"
               + rs.getString(5));
     }
   } catch (Exception e) {
     System.out.println("Error: " + e);
   }
 }
Esempio n. 3
0
  /** Test large batch behavior. */
  public void testLargeBatch() throws Exception {
    final int n = 5000;
    getConnection().close();

    Statement stmt = con.createStatement();
    stmt.executeUpdate("create table #testLargeBatch (val int)");
    stmt.executeUpdate("insert into #testLargeBatch (val) values (0)");

    PreparedStatement pstmt = con.prepareStatement("update #testLargeBatch set val=? where val=?");
    for (int i = 0; i < n; i++) {
      pstmt.setInt(1, i + 1);
      pstmt.setInt(2, i);
      pstmt.addBatch();
    }
    int counts[] = pstmt.executeBatch();
    //        System.out.println(pstmt.getWarnings());
    assertEquals(n, counts.length);
    for (int i = 0; i < n; i++) {
      assertEquals(1, counts[i]);
    }
    pstmt.close();

    ResultSet rs = stmt.executeQuery("select count(*) from #testLargeBatch");
    assertTrue(rs.next());
    assertEquals(1, rs.getInt(1));
    assertFalse(rs.next());
    rs.close();
    stmt.close();
  }
  /**
   * Remove a student from a particular course. Also Deletes all the quiz vizualisation files in the
   * student's directory which relates to the course. Caution: vizualisation file will be deleted
   * eventhough it also relates to another course if the student is also registered to that course.
   * (FIX ME!) Throws InvalidDBRequestException if the student is not registered in the course,
   * error occured during deletion, or other exception occured.
   *
   * @param username student's user name
   * @param courseID course id (course number + instructor name)
   * @throws InvalidDBRequestException
   */
  public void deleteStudent(String username, String courseID) throws InvalidDBRequestException {
    try {
      Class.forName(GaigsServer.DBDRIVER);
      db =
          DriverManager.getConnection(GaigsServer.DBURL, GaigsServer.DBLOGIN, GaigsServer.DBPASSWD);

      Statement stmt = db.createStatement();
      ResultSet rs;

      int count = 0;

      // check if student registered to the course
      rs =
          stmt.executeQuery(
              "select * from courseRoster where course_id = '"
                  + courseID
                  + "' and user_login = '******'");
      if (!rs.next())
        throw new InvalidDBRequestException("Student is not registered to the course");

      // remove student from the course
      count =
          stmt.executeUpdate(
              "delete from courseRoster where course_id = '"
                  + courseID
                  + "' and user_login = '******'");
      if (count != 1) throw new InvalidDBRequestException("Error occured during deletion!");

      // delete the quiz visualization files
      rs =
          stmt.executeQuery(
              "select distinct unique_id, s.test_name from scores s, courseTest t "
                  + "where s.test_name = t.test_name "
                  + "and course_id = '"
                  + courseID
                  + "' "
                  + "and user_login = '******'");
      while (rs.next()) {
        deleteVisualization(rs.getString(1), username, rs.getString(2));
        count =
            stmt.executeUpdate("delete from scores where unique_id = " + rs.getString(1).trim());
      }

      rs.close();
      stmt.close();
      db.close();
    } catch (SQLException e) {
      System.err.println("Invalid SQL in addstudent: " + e.getMessage());
      throw new InvalidDBRequestException("???");
    } catch (ClassNotFoundException e) {
      System.err.println("Driver Not Loaded");
      throw new InvalidDBRequestException("Internal Server Error");
    }
  }
Esempio n. 5
0
  public void doSQL() throws Exception {
    Class.forName("org.sqlite.JDBC");
    Connection conn = DriverManager.getConnection("jdbc:sqlite:test.db");
    Statement stat = conn.createStatement();
    stat.executeUpdate("drop table if exists people;");
    stat.executeUpdate("create table people (name, occupation);");
    PreparedStatement prep = conn.prepareStatement("insert into people values (?, ?);");

    prep.setString(1, "Gandhi");
    prep.setString(2, "politics");
    prep.addBatch();
    prep.setString(1, "Turing");
    prep.setString(2, "computers");
    prep.addBatch();
    prep.setString(1, "Wittgenstein");
    prep.setString(2, "smartypants");
    prep.addBatch();

    conn.setAutoCommit(false);
    prep.executeBatch();
    conn.setAutoCommit(true);

    ResultSet rs = stat.executeQuery("select * from people;");
    while (rs.next()) {
      System.out.println("name = " + rs.getString("name"));
      System.out.println("job = " + rs.getString("occupation"));
    }
    rs.close();
    conn.close();
  }
  /**
   * Delete a student from the database. Also deletes the student's folders. Throws
   * InvalidDBRequestException if any error in database connection.
   *
   * @param username student's user name
   * @throws InvalidDBRequestException
   */
  private void purgeStudent(String username) throws InvalidDBRequestException {
    try {
      Class.forName(GaigsServer.DBDRIVER);
      db =
          DriverManager.getConnection(GaigsServer.DBURL, GaigsServer.DBLOGIN, GaigsServer.DBPASSWD);

      Statement stmt = db.createStatement();
      int count;

      // delete from scores
      count = stmt.executeUpdate("delete from scores where user_login = '******'");

      // delete from student
      count = stmt.executeUpdate("delete from student where login = '******'");

      // delete student's folder
      File studentDir = new File("./StudentQuizzes/" + username);
      if (!(studentDir.delete())) {
        System.err.println("Error in deleting folder for student: " + username);
      }

      stmt.close();
      db.close();
    } catch (SQLException e) {
      System.err.println("Invalid SQL in addCourse: " + e.getMessage());
      throw new InvalidDBRequestException("??? ");
    } catch (ClassNotFoundException e) {
      System.err.println("Driver Not Loaded");
      throw new InvalidDBRequestException("Internal Server Error");
    }
  }
Esempio n. 7
0
  public synchronized void remove(Disciplina obj) throws Exception {

    // PROCEDIMENTOS PR�-Remoção
    // remove listas correspondentes
    Lista_ger listager = new Lista_ger();
    listager.removeByDisciplina(obj);

    // remove turmas correspondentes
    Turma_ger turmager = new Turma_ger();
    turmager.removeByDisciplina(obj);

    // Remoção
    // ------- Remove do banco -------
    Connection dbCon = BancoDados.abreConexao();
    Statement dbStmt = dbCon.createStatement();
    ResultSet dbRs;
    String str;

    str = "DELETE FROM Disciplina WHERE cod=" + obj.getCod();
    BancoDadosLog.log(str);
    dbStmt.executeUpdate(str);

    dbStmt.close();
    dbCon.close();

    // ------- Remove da mem�ria -------
    this.listaObj.removeElement(obj);

    // PROCEDIMENTOS P�S-Remoção

  }
Esempio n. 8
0
 static void specificAttributeMean() {
   try {
     Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
     con = DriverManager.getConnection("jdbc:odbc:jbdb", "system", "tiger");
     fill = con.createStatement();
     fill.executeUpdate(
         "UPDATE employ a set sal = (select AVG(sal) from employ where sal IS NOT NULL and grade = (select grade from employ b where sal IS NULL and a.grade=b.grade and ROWNUM <= 1)) where sal IS NULL");
     st = con.createStatement();
     rs = st.executeQuery("select * from employ");
     System.out.println(">>Sno\tName\tSalary\tGPF\tGrade");
     while (rs.next()) {
       System.out.println(
           ">>"
               + rs.getString(1)
               + "\t"
               + rs.getString(2)
               + "\t"
               + rs.getString(3)
               + "\t"
               + rs.getString(4)
               + "\t"
               + rs.getString(5));
     }
   } catch (Exception e) {
     System.out.println("Error: " + e);
   }
 }
Esempio n. 9
0
 static void globalConstant() {
   try {
     Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
     con = DriverManager.getConnection("jdbc:odbc:jbdb", "system", "tiger");
     fill = con.createStatement();
     fill.executeUpdate("UPDATE employ set sal = " + GlobalConstant + " where sal IS NULL");
     // fill.executeUpdate("UPDATE employ set sal = COALESCE(sal," + GlobalConstant + ")");
     // System.out.println("Entered..!");
     st = con.createStatement();
     rs = st.executeQuery("select * from employ");
     System.out.println("Sno\tName\tSalary\tGPF\tGrade");
     while (rs.next()) {
       System.out.println(
           ">>"
               + rs.getString(1)
               + "\t"
               + rs.getString(2)
               + "\t"
               + rs.getString(3)
               + "\t"
               + rs.getString(4)
               + "\t"
               + rs.getString(5));
     }
   } catch (Exception e) {
     System.out.println("Error: " + e);
   }
 }
 /**
  * Sets the user to run as. This is for the case where the request was generated by the user and
  * so the worker must set this value later.
  *
  * @param cq_id id of this entry in the queue
  * @param user user to run the jobs as
  */
 public void setRunAs(long cq_id, String user) throws MetaException {
   try {
     Connection dbConn = getDbConn();
     try {
       Statement stmt = dbConn.createStatement();
       String s = "update COMPACTION_QUEUE set cq_run_as = '" + user + "' where cq_id = " + cq_id;
       LOG.debug("Going to execute update <" + s + ">");
       if (stmt.executeUpdate(s) != 1) {
         LOG.error("Unable to update compaction record");
         LOG.debug("Going to rollback");
         dbConn.rollback();
       }
       LOG.debug("Going to commit");
       dbConn.commit();
     } catch (SQLException e) {
       LOG.error("Unable to update compaction queue, " + e.getMessage());
       try {
         LOG.debug("Going to rollback");
         dbConn.rollback();
       } catch (SQLException e1) {
       }
       detectDeadlock(e, "setRunAs");
     } finally {
       closeDbConn(dbConn);
     }
   } catch (DeadlockException e) {
     setRunAs(cq_id, user);
   } finally {
     deadlockCnt = 0;
   }
 }
Esempio n. 11
0
  void processChatUpdate(ChatUpdateMessage message) {
    String g, m, k;
    m = message.getUsername();
    g = message.getMessage();
    k = message.getRec();

    try {

      String url = "jdbc:mysql://localhost:3306/chat";
      Connection conn = DriverManager.getConnection(url, "root", "root");
      Statement st = conn.createStatement();
      st.executeUpdate(
          "INSERT INTO Log(User,Message,Recepient) "
              + "VALUE ('"
              + m
              + "','"
              + g
              + "','"
              + k
              + "')");

    } catch (Exception e) {
      System.err.println("Got an exception! ");
      System.err.println(e.getMessage());
    }

    this.addMessage(message.getMessage(), message.getRec());
  }
Esempio n. 12
0
  public void upgradeBaseSchema(Connection conn, int currentVersion) {
    if (!isLoaded()) {
      throw new TajoInternalError("Database schema files are not loaded.");
    }

    final List<SchemaPatch> candidatePatches = new ArrayList<>();
    Statement stmt;

    for (SchemaPatch patch : this.catalogStore.getPatches()) {
      if (currentVersion >= patch.getPriorVersion()) {
        candidatePatches.add(patch);
      }
    }

    Collections.sort(candidatePatches);
    try {
      stmt = conn.createStatement();
    } catch (SQLException e) {
      throw new TajoInternalError(e);
    }

    for (SchemaPatch patch : candidatePatches) {
      for (DatabaseObject object : patch.getObjects()) {
        try {
          stmt.executeUpdate(object.getSql());
          LOG.info(object.getName() + " " + object.getType() + " was created or altered.");
        } catch (SQLException e) {
          throw new TajoInternalError(e);
        }
      }
    }

    CatalogUtil.closeQuietly(stmt);
  }
Esempio n. 13
0
  public static void customStartAll(Connection conn) throws SQLException {
    String method = "customStartAll";
    int location = 1000;
    try {
      Statement stmt = conn.createStatement();

      int id = 0;
      int gpfdistPort = 0;
      String strSQL = "SELECT id\n";
      strSQL += "FROM os.custom_sql";

      ResultSet rs = stmt.executeQuery(strSQL);
      while (rs.next()) {
        id = rs.getInt(1);
        gpfdistPort = GpfdistRunner.customStart(OSProperties.osHome);

        strSQL = "INSERT INTO os.ao_custom_sql\n";
        strSQL +=
            "(id, table_name, columns, column_datatypes, sql_text, source_type, source_server_name, source_instance_name, source_port, source_database_name, source_user_name, source_pass, gpfdist_port)\n";
        strSQL +=
            "SELECT id, table_name, columns, column_datatypes, sql_text, source_type, source_server_name, source_instance_name, source_port, source_database_name, source_user_name, source_pass, "
                + gpfdistPort
                + "\n";
        strSQL += "FROM os.custom_sql\n";
        strSQL += "WHERE id = " + id;

        stmt.executeUpdate(strSQL);
      }
    } catch (SQLException ex) {
      throw new SQLException(
          "(" + myclass + ":" + method + ":" + location + ":" + ex.getMessage() + ")");
    }
  }
Esempio n. 14
0
  public static void failJobs(Connection conn) throws SQLException {
    String method = "failJobs";
    int location = 1000;
    try {
      Statement stmt = conn.createStatement();

      String strSQL =
          "INSERT INTO os.ao_queue (queue_id, status, queue_date, start_date, end_date, "
              + "error_message, num_rows, id, refresh_type, target_schema_name, target_table_name, target_append_only, "
              + "target_compressed, target_row_orientation, source_type, source_server_name, source_instance_name, "
              + "source_port, source_database_name, source_schema_name, source_table_name, source_user_name, "
              + "source_pass, column_name, sql_text, snapshot) "
              + "SELECT queue_id, 'failed' as status, queue_date, start_date, now() as end_date, "
              + "'Outsourcer stop requested' as error_message, num_rows, id, refresh_type, target_schema_name, "
              + "target_table_name, target_append_only, target_compressed, target_row_orientation, source_type, "
              + "source_server_name, source_instance_name, source_port, source_database_name, source_schema_name, "
              + "source_table_name, source_user_name, source_pass, column_name, sql_text, snapshot "
              + "FROM os.queue WHERE status = 'queued'";

      stmt.executeUpdate(strSQL);

    } catch (SQLException ex) {
      throw new SQLException(
          "(" + myclass + ":" + method + ":" + location + ":" + ex.getMessage() + ")");
    }
  }
 private static void truncateTables(Collection<String> tables, Connection connection) {
   try (Statement statement = connection.createStatement()) {
     statement.executeUpdate("TRUNCATE " + Joiner.on(", ").join(tables) + " CASCADE");
   } catch (SQLException e) {
     throw new RuntimeException(e);
   }
 }
Esempio n. 16
0
  /**
   * Deletes an instructor from the database. Deletes the instructor's courses by invoking the
   * deleteCourse method. Throws InvalidDBRequestException if instructor not in the database or
   * other database connection problems.
   *
   * @see deleteCourse
   * @param instructor instructor's user name
   * @throws InvalidDBRequestException
   */
  public void deleteInstructor(String instructor) throws InvalidDBRequestException {
    try {
      Class.forName(GaigsServer.DBDRIVER);
      db =
          DriverManager.getConnection(GaigsServer.DBURL, GaigsServer.DBLOGIN, GaigsServer.DBPASSWD);

      Statement stmt = db.createStatement();
      int count;

      // delete the instructor's courses
      ResultSet rs =
          stmt.executeQuery(
              "select course_num from course where instructor = '" + instructor + "'");
      while (rs.next()) deleteCourse(rs.getString(1).trim(), instructor);

      // delete the instructor's record
      count = stmt.executeUpdate("delete from instructor where login ='******'");

      rs.close();
      stmt.close();
      db.close();
    } catch (SQLException e) {
      System.err.println("Invalid SQL in addCourse: " + e.getMessage());
      throw new InvalidDBRequestException("??? ");
    } catch (ClassNotFoundException e) {
      System.err.println("Driver Not Loaded");
      throw new InvalidDBRequestException("Internal Server Error");
    }
  }
Esempio n. 17
0
  private synchronized void init() throws SQLException {
    if (isClosed) return;

    // do tables exists?
    Statement stmt = conn.createStatement();
    ResultSet rs = stmt.executeQuery(TABLE_NAMES_SELECT_STMT);

    ArrayList<String> missingTables = new ArrayList(TABLES.keySet());
    while (rs.next()) {
      String tableName = rs.getString("name");
      missingTables.remove(tableName);
    }

    for (String missingTable : missingTables) {
      try {
        Statement createStmt = conn.createStatement();
        // System.out.println("Adding table "+ missingTable);
        createStmt.executeUpdate(TABLES.get(missingTable));
        createStmt.close();

      } catch (Exception e) {
        System.err.println(e.getClass().getName() + ": " + e.getMessage());
      }
    }
  }
  /**
   * Preconditions: 1. xid is known to the RM or it's in prepared state
   *
   * <p>Implementation deficiency preconditions: 1. xid must be associated with this connection if
   * it's not in prepared state.
   *
   * <p>Postconditions: 1. Transaction is rolled back and disassociated from connection
   */
  public void rollback(Xid xid) throws XAException {
    if (logger.logDebug()) debug("rolling back xid = " + xid);

    // We don't explicitly check precondition 1.

    try {
      if (currentXid != null && xid.equals(currentXid)) {
        state = STATE_IDLE;
        currentXid = null;
        conn.rollback();
        conn.setAutoCommit(localAutoCommitMode);
      } else {
        String s = RecoveredXid.xidToString(xid);

        conn.setAutoCommit(true);
        Statement stmt = conn.createStatement();
        try {
          stmt.executeUpdate("ROLLBACK PREPARED '" + s + "'");
        } finally {
          stmt.close();
        }
      }
    } catch (SQLException ex) {
      throw new PGXAException(
          GT.tr("Error rolling back prepared transaction"), ex, XAException.XAER_RMERR);
    }
  }
Esempio n. 19
0
 static void probableValue() {
   try {
     Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
     con = DriverManager.getConnection("jdbc:odbc:jbdb", "system", "tiger");
     Statement freqQuery = con.createStatement();
     ResultSet freq =
         freqQuery.executeQuery(
             "select sal,count(*) as total from employ group by sal order by total desc");
     if (freq.next()) {
       fill = con.createStatement();
       fill.executeUpdate("UPDATE employ set sal = COALESCE(sal," + freq.getInt(1) + ")");
     }
     st = con.createStatement();
     rs = st.executeQuery("select * from employ");
     System.out.println(">>Sno\tName\tSalary\tGPF\tGrade");
     while (rs.next()) {
       System.out.println(
           ">>"
               + rs.getString(1)
               + "\t"
               + rs.getString(2)
               + "\t"
               + rs.getString(3)
               + "\t"
               + rs.getString(4)
               + "\t"
               + rs.getString(5));
     }
   } catch (Exception e) {
     System.out.println("Error: " + e);
   }
 }
  /**
   * Preconditions: 1. xid must be in prepared state in the server
   *
   * <p>Implementation deficiency preconditions: 1. Connection must be in idle state
   *
   * <p>Postconditions: 1. Transaction is committed
   */
  private void commitPrepared(Xid xid) throws XAException {
    try {
      // Check preconditions. The connection mustn't be used for another
      // other XA or local transaction, or the COMMIT PREPARED command
      // would mess it up.
      if (state != STATE_IDLE || conn.getTransactionState() != ProtocolConnection.TRANSACTION_IDLE)
        throw new PGXAException(
            GT.tr("Not implemented: 2nd phase commit must be issued using an idle connection"),
            XAException.XAER_RMERR);

      String s = RecoveredXid.xidToString(xid);

      localAutoCommitMode = conn.getAutoCommit();
      conn.setAutoCommit(true);
      Statement stmt = conn.createStatement();
      try {
        stmt.executeUpdate("COMMIT PREPARED '" + s + "'");
      } finally {
        stmt.close();
        conn.setAutoCommit(localAutoCommitMode);
      }
    } catch (SQLException ex) {
      throw new PGXAException(
          GT.tr("Error committing prepared transaction"), ex, XAException.XAER_RMERR);
    }
  }
Esempio n. 21
0
  public void saveSentMessage(COutgoingMessage message) throws Exception {
    Statement sqlCmd;

    if (connection != null) {
      sqlCmd =
          connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
      sqlCmd.executeUpdate(
          "insert into sms_out (recipient, text, dispatch_date, flash_sms, status_report, src_port, dst_port, validity_period) values ('"
              + message.getRecipient()
              + "', '"
              + message.getText().replaceAll("'", "''")
              + "', "
              + escapeDate(message.getDate(), true)
              + ", "
              + (message.getFlashSms() ? 1 : 0)
              + ", "
              + (message.getStatusReport() ? 1 : 0)
              + ", "
              + message.getSourcePort()
              + ", "
              + message.getDestinationPort()
              + ", "
              + message.getValidityPeriod()
              + ")");
      connection.commit();
      sqlCmd.close();
    }
  }
Esempio n. 22
0
  public synchronized Disciplina inclui(String nome, String descricao) throws Exception {

    // ------- Testa consist�ncia dos dados -------
    String testeCons = testaConsistencia(null, nome, descricao);
    if (testeCons != null)
      throw new Exception("não foi possível inserir devido ao campo " + testeCons + "");

    // ------- Insere na base de dados -------
    // Inicia a conexão com a base de dados
    Connection dbCon = BancoDados.abreConexao();
    Statement dbStmt = dbCon.createStatement();
    ResultSet dbRs;
    String str;

    // Pega Id maximo
    long maxId = 1;
    str = "SELECT Max(cod) AS maxId From Disciplina";
    BancoDadosLog.log(str);
    dbRs = dbStmt.executeQuery(str);
    if (dbRs.next()) {
      maxId = dbRs.getLong("maxId");
      maxId++;
    }
    String id = Long.toString(maxId);

    nome = StringConverter.toDataBaseNotation(nome);

    // Insere o elemento na base de dados
    str = "INSERT INTO Disciplina (cod, nome, descricao, desativada)";
    str +=
        " VALUES ("
            + id
            + ",'"
            + nome
            + "'"
            + ",'"
            + StringConverter.toDataBaseNotation(descricao)
            + "',0)";

    BancoDadosLog.log(str);
    dbStmt.executeUpdate(str);

    // Finaliza conexao
    dbStmt.close();
    dbCon.close();

    // ------- Insere na mem�ria -------
    // Cria um novo objeto
    Disciplina obj = new Disciplina(id, nome, descricao, false);

    // Insere o objeto na lista do gerente
    this.listaObj.addElement(obj);

    // ---- Cria uma nova turma ----
    Turma_ger turmager = new Turma_ger();
    turmager.inclui("Turma 1", "", obj);

    return obj;
  }
Esempio n. 23
0
  // Query to store an image
  protected void storeQuery(int image_id, int line, Statement st, String data) throws Exception {
    String query = "insert into image_store values(" + image_id + ", " + line + ", '" + data + "')";

    // Print out the query for debug.
    // System.err.println(query);

    st.executeUpdate(query);
  }
Esempio n. 24
0
 public void DbInsertLoginCar(List<LoginCar> list) throws SQLException {
   Iterator<LoginCar> iter = list.iterator();
   LoginCar lc = new LoginCar();
   while (iter.hasNext()) {
     lc = iter.next();
     String sql = "insert into CarInfo values(" + lc.getLoginId() + "," + lc.getCarId() + ");";
     state.executeUpdate(sql);
   }
 }
 public static void turnOnGFEAuthorization(Connection conn, String sql) {
   Log.getLogWriter().info("turn on authorization statement in GFE");
   try {
     Statement stmt = conn.createStatement();
     stmt.executeUpdate(sql);
     conn.commit();
   } catch (SQLException se) {
     SQLHelper.handleSQLException(se);
   }
 }
Esempio n. 26
0
  public void utiliserPopo(objet potion) {
    int val = 0;
    int ancVal = 0;
    String carac = null;
    try {
      stmt.executeUpdate(
          "update equipement SET estEquipe = true where idObjet ='"
              + potion.idObjet()
              + "' and idTroll="
              + idTroll);
      ResultSet rset =
          stmt.executeQuery(
              "select caracteristique from carac where idObjet='" + potion.idObjet() + "'");
      while (rset.next()) {
        carac = rset.getString("caracteristique");
      }

      rset =
          conn.createStatement()
              .executeQuery("select valeur from carac where idObjet='" + potion.idObjet() + "'");
      while (rset.next()) {
        val = rset.getInt("valeur");
      }

      rset = stmt.executeQuery("select " + carac + " from troll where idTroll=" + idTroll);
      while (rset.next()) {
        ancVal = rset.getInt(carac);
      }
      stmt.executeUpdate(
          "update troll SET " + carac + " = " + (ancVal + val) + "where idTroll=" + idTroll);
      rset = stmt.executeQuery("select paRestants from troll where idTroll=" + idTroll);
      while (rset.next()) {
        ancVal = rset.getInt("paRestants");
      }
      stmt.executeUpdate(
          "update troll SET paRestants = " + (ancVal - 1) + " where idTroll=" + idTroll);
      tabPopoEnCours.put(potion.idObjet(), potion);
      paRestants = paRestants - 1;
    } catch (SQLException E) {
      System.err.println("SQLException: " + E.getMessage());
      System.err.println("SQLState:     " + E.getSQLState());
    }
  }
 public int ejecutaActualizacion(String actualizacion) throws SQLException {
   int i = comprobar();
   int res = 0;
   try {
     stmt = conexion.get(i).createStatement();
     res = stmt.executeUpdate(actualizacion);
   } catch (SQLException ex) {
     Logger.getLogger(BaseDatos.class.getName()).log(Level.SEVERE, null, ex);
   }
   return res;
 }
Esempio n. 28
0
 public int DbInsertLoginInfo(LoginInfo li) throws SQLException {
   String sql =
       "insert into LoginInfo values(default,'"
           + li.getLoginName()
           + "','"
           + li.getLoginPswd()
           + "',"
           + li.getLoginNum()
           + ");";
   return state.executeUpdate(sql);
 }
Esempio n. 29
0
  public static void clearTable() {
    connectDb();
    String sql = "delete from " + tablename + ";";
    try {
      query.executeUpdate(sql);

    } catch (SQLException e) {
      System.out.println("SQL Exception: " + e);
      System.exit(1);
    }
    System.out.println("Table Cleared Successfully");
  }
Esempio n. 30
0
  void initWithTestData(final ConnectionManager connectionManager) {

    createSchema(connectionManager);

    Connection connection = null;
    Statement statement = null;
    try {
      connection = connectionManager.getConnection(null);
      statement = connection.createStatement();
      assertEquals(statement.executeUpdate("INSERT INTO " + TABLE_NAME + " values (1, 'abs')"), 1);
      assertEquals(statement.executeUpdate("INSERT INTO " + TABLE_NAME + " values (1, 'gps')"), 1);
      assertEquals(
          statement.executeUpdate("INSERT INTO " + TABLE_NAME + " values (2, 'airbags')"), 1);
      assertEquals(statement.executeUpdate("INSERT INTO " + TABLE_NAME + " values (3, 'abs')"), 1);
    } catch (Exception e) {
      throw new IllegalStateException("Unable to initialize test database", e);
    } finally {
      DBUtils.closeQuietly(connection);
      DBUtils.closeQuietly(statement);
    }
  }