Java Code Examples for java.sql.PreparedStatement.execute()

The following are Jave code examples for showing how to use execute() of the java.sql.PreparedStatement class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: spr   File: SqlInserts.java   View Source Code Vote up 6 votes
public static void insertNivel(Nivel nivel){
	try {
		Connection conn=ConnectionConfiguration.conectar();
	   	
		String query = " insert into nivel (numero_fila,anho,cod_nivel,nombre,abrev,es_imputable)"
		+ " values (?, ?, ?, ?, ?, ?)";
		
		PreparedStatement insert = conn.prepareStatement(query);
		
		insert.setInt (1, nivel.getNumeroFila());
		insert.setInt (2, nivel.getAnio());
		insert.setInt (3, nivel.getNivel());
		insert.setString (4, nivel.getNombreNivel());
		insert.setString (5, nivel.getAbrevNivel());
		insert.setString (6, nivel.getEsImputable());
							
		insert.execute();
		   
		conn.close();
	} catch (SQLException e) {e.printStackTrace();}
		
}
 
Example 2
Project: spr   File: SqlInserts.java   View Source Code Vote up 6 votes
public static void insertProyectoSnipAutorizado(ProyectoSNIPAutorizado proyectoSnipAutorizado){
	try {
		Connection conn=ConnectionConfiguration.conectar();
	   	
		String query = " insert into proyecto_snip_autorizado (anho, monto, entidad_id, entidad_nivel_id, proyecto_snip_id, organismo_financiador_id, fuente_financiamiento_id )"
		+ " values (?, ?, ?, ?, ?, ?, ?, ?)";
		
		PreparedStatement insert = conn.prepareStatement(query);
		insert.setInt (1, proyectoSnipAutorizado.getAnio());
		insert.setDouble (2, proyectoSnipAutorizado.getMonto());
		insert.setDouble (3, proyectoSnipAutorizado.getEntidad());
		insert.setDouble (4, proyectoSnipAutorizado.getNivel());
		insert.setDouble (5, proyectoSnipAutorizado.getCodigoSnip());
		insert.setInt (6, proyectoSnipAutorizado.getCodOrganismoFinanciador());
		insert.setInt (7, proyectoSnipAutorizado.getCodFuenteFinanciamiento());
		
		insert.execute();
		   
		conn.close();
	} catch (SQLException e) {e.printStackTrace();}
		
}
 
Example 3
Project: freemoz   File: QueueDAO.java   View Source Code Vote up 6 votes
public synchronized boolean addSubmission(SubmissionDTO submissionDTO) {
    Connection connection;
    PreparedStatement preparedStatement = null;

    try {
        connection = this.dbConfig.getConnection();
        preparedStatement = connection.prepareStatement("INSERT INTO \"main\".\"submission\" (\"bucket\", \"user\",\"timeout\",\"status\",\"data\") VALUES (?,'',?,?,?)");
        preparedStatement.setString(1, "A");
        preparedStatement.setLong(2, System.currentTimeMillis());
        preparedStatement.setInt(3, 0);
        preparedStatement.setString(4, gson.toJson(submissionDTO));
        preparedStatement.execute();
    }
    catch(SQLException ex) {
        return false;
    }
    finally {
        this.helpers.closeQuietly(preparedStatement);
    }

    return true;
}
 
Example 4
Project: s-store   File: TransferDb.java   View Source Code Vote up 6 votes
/**
 * Method declaration
 *
 *
 * @param type
 * @param r
 * @param p
 *
 * @throws SQLException
 */
private void transferRow(TransferResultSet r, PreparedStatement p,
                         int len,
                         int[] types)
                         throws DataAccessPointException, SQLException {

    for (int i = 1; i <= len; i++) {
        int    t = types[i];
        Object o = r.getObject(i);

        if (o == null) {
            if (p != null) {
                p.setNull(i, t);
            }
        } else {
            o = helper.convertColumnValue(o, i, t);

            p.setObject(i, o);
        }
    }

    if (p != null) {
        p.execute();
    }
}
 
Example 5
Project: spr   File: SqlInserts.java   View Source Code Vote up 6 votes
public static void insertTipoPresupuesto(TipoPresupuesto tipoPresupuesto, String usuarioResponsable){
	try {
		Connection conn=ConnectionConfiguration.conectar();
	   	
		String query = " insert into tipo_presupuesto (id,nombre,abrev,descipcion,anho,numero_fila, usuario_responsable)"
		+ " values (?, ?, ?, ?, ?, ?, ?)";
		
		PreparedStatement insert = conn.prepareStatement(query);
		insert.setInt (1, tipoPresupuesto.getId());
		insert.setString (2, tipoPresupuesto.getNombre());
		insert.setString (3, tipoPresupuesto.getAbrev());
		insert.setString (4, tipoPresupuesto.getDescripcion());
		insert.setInt (5, tipoPresupuesto.getAnho());
		insert.setInt (6, tipoPresupuesto.getNumero_fila());
		insert.setString (7, usuarioResponsable);
					
		insert.execute();
		   
		conn.close();
	} catch (SQLException e) {e.printStackTrace();}
}
 
Example 6
Project: bbm487s2017g1   File: Query.java   View Source Code Vote up 6 votes
public static boolean deleteWaitListBook(int userId, int book_id){
    PreparedStatement statement;
    String query = String.format("DELETE FROM %s WHERE user_id=? AND book_id=?", waitListTable);

    try {
        statement = MySQL.getInstance().getConnection().prepareStatement(query);
        statement.setInt(1,userId);
        statement.setInt(2,book_id);

        statement.execute();
        return true;

    }catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}
 
Example 7
Project: spr   File: SqlInserts.java   View Source Code Vote up 6 votes
public static void insertUnidadMedida(UnidadMedida unidadMedida){
	try {
		Connection conn=ConnectionConfiguration.conectar();
	   	
		String query = " insert into unidad_medida (id,nombre,abrev)"
		+ " values (?, ?, ?)";
		
		PreparedStatement insert = conn.prepareStatement(query);
		insert.setInt (1, unidadMedida.getCodigoUnidadMedida());
		insert.setString (2, unidadMedida.getNombre());
		insert.setString (3, unidadMedida.getAbreviacion());
					
		insert.execute();
		   
		conn.close();
	} catch (SQLException e) {e.printStackTrace();}
}
 
Example 8
Project: ralasafe   File: EmployeeManager.java   View Source Code Vote up 5 votes
public void deleteEmployee( int deptId ) {
	Connection conn=null;
	PreparedStatement pstmt=null;
	
	try {
		conn=DemoUtil.getConnection();
		pstmt=conn.prepareStatement( DELETE_SQL );
		pstmt.setInt( 1, deptId );
		pstmt.execute();
	} catch( SQLException e ) {
		e.printStackTrace();
	} finally {
		DBUtil.close( pstmt, conn );
	}
}
 
Example 9
Project: ramus   File: FuckRestore.java   View Source Code Vote up 5 votes
/**
 * @param args
 * @throws SQLException
 */
public static void main(String[] args) throws SQLException {
    try {
        Class.forName("org.postgresql.Driver");
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }

    Connection pub = DriverManager.getConnection(
            "jdbc:postgresql://127.0.0.1/ramus_public", "postgres",
            "postgres");

    Connection dev = DriverManager.getConnection(
            "jdbc:postgresql://127.0.0.1/ramus_public_dev", "postgres",
            "postgres");

    Statement st = dev.createStatement();
    ResultSet rs = st.executeQuery("SELECT * FROM ramus_cattle_tasks");
    PreparedStatement ps = pub.prepareStatement("UPDATE ramus_cattle_tasks SET name=? WHERE task_id=?");
    int i = 0;
    while (rs.next()) {
        ps.setString(1, rs.getString("name"));
        ps.setLong(2, rs.getLong("task_id"));
        ps.execute();
        i++;
        if (i % 1000 == 0)
            System.out.println(i);
    }
    rs.close();
    st.close();
    ps.close();
    pub.commit();

}
 
Example 10
Project: avengers-db   File: TeamDAO.java   View Source Code Vote up 5 votes
public void deleteTeam(int id) throws SQLException {
	Connection connect = connectToMySQL();
	
	String queryth = "DELETE FROM `team_hero` WHERE team_id=?";
	PreparedStatement stath = connect.prepareStatement(queryth, Statement.RETURN_GENERATED_KEYS);
	stath.setInt(1, id);
	stath.execute();
	
	String query = "DELETE FROM `team` WHERE team_id=?";
	PreparedStatement stateam = connect.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
	stateam.setInt(1, id);
	stateam.execute();
	connect.close();
}
 
Example 11
Project: ProyectoPacientes   File: StatementsTest.java   View Source Code Vote up 5 votes
/**
 * Tests for ServerPreparedStatement.setNCharacterSteam()
 * 
 * @throws Exception
 */
public void testSetNCharacterStreamServer() throws Exception {
    createTable("testSetNCharacterStreamServer", "(c1 NATIONAL CHARACTER(10)) ENGINE=InnoDB");
    Properties props1 = new Properties();
    props1.put("useServerPrepStmts", "true"); // use server-side prepared statement
    props1.put("useUnicode", "true");
    props1.put("characterEncoding", "latin1"); // ensure charset isn't utf8 here
    Connection conn1 = getConnectionWithProps(props1);
    PreparedStatement pstmt1 = conn1.prepareStatement("INSERT INTO testSetNCharacterStreamServer (c1) VALUES (?)");
    try {
        pstmt1.setNCharacterStream(1, new StringReader("aaa"), 3);
        fail();
    } catch (SQLException e) {
        // ok
        assertEquals("Can not call setNCharacterStream() when connection character set isn't UTF-8", e.getMessage());
    }
    pstmt1.close();
    conn1.close();

    createTable("testSetNCharacterStreamServer", "(c1 LONGTEXT charset utf8) ENGINE=InnoDB");
    Properties props2 = new Properties();
    props2.put("useServerPrepStmts", "true"); // use server-side prepared statement
    props2.put("useUnicode", "true");
    props2.put("characterEncoding", "UTF-8"); // ensure charset is utf8 here
    Connection conn2 = getConnectionWithProps(props2);
    PreparedStatement pstmt2 = conn2.prepareStatement("INSERT INTO testSetNCharacterStreamServer (c1) VALUES (?)");
    pstmt2.setNCharacterStream(1, new StringReader(new String(new char[81921])), 81921); // 10 Full Long Data Packet's chars + 1 char
    pstmt2.execute();
    ResultSet rs2 = this.stmt.executeQuery("SELECT c1 FROM testSetNCharacterStreamServer");
    rs2.next();
    assertEquals(new String(new char[81921]), rs2.getString(1));
    rs2.close();
    pstmt2.close();
    conn2.close();
}
 
Example 12
Project: sstore-soft   File: ClientStatsSqlLoader.java   View Source Code Vote up 5 votes
public void start(long startTime, int leaderAddress) throws SQLException {
    Timestamp timestamp = new Timestamp(startTime);
    if (LOG.isDebugEnabled())
        LOG.debug(String.format("Cluster Start Time: %s [%d]", timestamp, startTime));
    
    PreparedStatement instanceStmt =
        m_conn.prepareStatement(
                createInstanceStatement,
                PreparedStatement.RETURN_GENERATED_KEYS);
    insertConnectionStatsStmt = m_conn.prepareStatement(insertConnectionStatsStatement);
    insertProcedureStatsStmt = m_conn.prepareStatement(insertProcedureStatsStatement);
    instanceStmt.setTimestamp( 1, timestamp);
    instanceStmt.setInt( 2, leaderAddress);
    instanceStmt.setString( 3, m_applicationName);
    if (m_subApplicationName != null) {
        instanceStmt.setString( 4, m_subApplicationName);
    } else {
        instanceStmt.setNull( 4, Types.VARCHAR);
    }
    instanceStmt.setInt(5, CatalogUtil.getNumberOfHosts(m_settings.getCatalog()));
    instanceStmt.setInt(6, CatalogUtil.getNumberOfSites(m_settings.getCatalog()));
    instanceStmt.setInt(7, CatalogUtil.getNumberOfPartitions(m_settings.getCatalog()));
    instanceStmt.execute();
    ResultSet results = instanceStmt.getGeneratedKeys();
    while (results.next()) {
        m_instanceId = results.getInt( 1 );
    }
    results.close();
    instanceStmt.close();
    if (m_instanceId < 0) {
        throw new SQLException("Unable to generate an instance id to identify this client");
    }
    insertConnectionStatsStmt.setInt( 1, m_instanceId);
    insertProcedureStatsStmt.setInt( 1, m_instanceId);
    m_conn.commit();
    m_loadThread.setDaemon(true);
    m_loadThread.start();
    if (LOG.isDebugEnabled())
        LOG.debug("ClientStatsLoader has been started");
}
 
Example 13
Project: ProyectoTestUnitario   File: CrearEjercicio.java   View Source Code Vote up 5 votes
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
    try {
        Random rm = new Random();
        Ejercicio ejNuevo = new Ejercicio();
        
        ejNuevo.codEj = rm.nextInt(50000);
        ejNuevo.expresion= jTextField1.getText();
        ejNuevo.resultado = parseInt(jTextField2.getText());
        ejNuevo.nivelEj.numeroNivel=parseInt((String) jComboBox1.getSelectedItem());
        ejNuevo.puntaje= parseInt(jTextField3.getText()) ;
        
        ConectarBD con = new ConectarBD();
        Connection cn=null;
        cn = con.getCon();
        
        String sql = " INSERT INTO ejercicio (codEj, expresion, resultado, numNivel, puntaje)"
    + " values (?, ?, ?, ?, ?)";
        
        PreparedStatement st = cn.prepareStatement(sql);
       
        
         st.setInt(1, ejNuevo.codEj);
         st.setString(2, ejNuevo.expresion);
         st.setInt(3, ejNuevo.resultado);
         st.setInt(4, ejNuevo.nivelEj.numeroNivel);
         st.setInt(5, ejNuevo.puntaje);
        
        
         st.execute();
    } catch (SQLException ex) {
        Logger.getLogger(CrearEjercicio.class.getName()).log(Level.SEVERE, null, ex);
         JOptionPane.showMessageDialog(null, "No se ha podido Guardar.");
    }
    
    JOptionPane.showMessageDialog(null, "Se ha guardado correctamente.");
    this.setVisible(false);
    
}
 
Example 14
Project: parabuild-ci   File: TestCacheSize.java   View Source Code Vote up 5 votes
void selectZip() {

        StopWatch        sw        = new StopWatch();
        java.util.Random randomgen = new java.util.Random();
        int              i         = 0;
        boolean          slow      = false;

        try {
            PreparedStatement ps = cConnection.prepareStatement(
                "SELECT TOP 1 firstname,lastname,zip,filler FROM test WHERE zip = ?");

            for (; i < bigops; i++) {
                ps.setInt(1, nextIntRandom(randomgen, smallrows));
                ps.execute();

                if ((i + 1) == 100 && sw.elapsedTime() > 50000) {
                    slow = true;
                }

                if (reportProgress && (i + 1) % 10000 == 0
                        || (slow && (i + 1) % 100 == 0)) {
                    System.out.println("Select " + (i + 1) + " : "
                                       + sw.elapsedTime() + " rps: "
                                       + (i * 1000 / (sw.elapsedTime() + 1)));
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        long time = sw.elapsedTime();
        long rate = ((long) i * 1000) / (time + 1);

        storeResult("select random zip", i, time, rate);
        System.out.println("select time for random zip " + i + " rows  -- "
                           + time + " ms -- " + rate + " tps");
    }
 
Example 15
Project: Rubicon   File: UserMusicSQL.java   View Source Code Vote up 5 votes
public void set(String type, String value) {
    createDefaultEntryIfNotExist();
    try {
        if (connection.isClosed())
            mySQL.connect();
        PreparedStatement ps = connection.prepareStatement("UPDATE music_users SET " + type + "=? WHERE userid=?");
        ps.setString(1, value);
        ps.setString(2, user.getId());
        ps.execute();
    } catch (SQLException e) {
        Logger.error(e);
    }
}
 
Example 16
Project: lams   File: ToolDBDeployTask.java   View Source Code Vote up 5 votes
private void updateToolLibraryId(long newToolId, long libraryId, Connection conn) throws DeployException {
PreparedStatement stmt = null;
try {
    stmt = conn.prepareStatement("UPDATE lams_tool SET learning_library_id = ? WHERE tool_id = ?");
    stmt.setLong(1, libraryId);
    stmt.setLong(2, newToolId);
    stmt.execute();

} catch (SQLException sqlex) {
    throw new DeployException("Could not update library id into tool", sqlex);
} finally {
    DbUtils.closeQuietly(stmt);
}
   }
 
Example 17
Project: ramus   File: IEngineImpl.java   View Source Code Vote up 5 votes
@Override
public void deleteBranch(long branch) {
    qualifeirsCache.clear();
    try {
        PreparedStatement ps = template.getPreparedStatement("DELETE FROM "
                        + IEngineImpl.this.prefix + "branches WHERE branch_id=?",
                false);
        ps.setLong(1, branch);
        ps.execute();
        ps.close();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 18
Project: hadoop   File: DBCountPageView.java   View Source Code Vote up 4 votes
/**
 * Populates the Access table with generated records.
 */
private void populateAccess() throws SQLException {

  PreparedStatement statement = null ;
  try {
    statement = connection.prepareStatement(
        "INSERT INTO Access(url, referrer, time)" +
        " VALUES (?, ?, ?)");

    Random random = new Random();

    int time = random.nextInt(50) + 50;

    final int PROBABILITY_PRECISION = 100; //  1 / 100 
    final int NEW_PAGE_PROBABILITY  = 15;  //  15 / 100


    //Pages in the site :
    String[] pages = {"/a", "/b", "/c", "/d", "/e", 
                      "/f", "/g", "/h", "/i", "/j"};
    //linkMatrix[i] is the array of pages(indexes) that page_i links to.  
    int[][] linkMatrix = {{1,5,7}, {0,7,4,6,}, {0,1,7,8}, 
      {0,2,4,6,7,9}, {0,1}, {0,3,5,9}, {0}, {0,1,3}, {0,2,6}, {0,2,6}};

    //a mini model of user browsing a la pagerank
    int currentPage = random.nextInt(pages.length); 
    String referrer = null;

    for(int i=0; i<time; i++) {

      statement.setString(1, pages[currentPage]);
      statement.setString(2, referrer);
      statement.setLong(3, i);
      statement.execute();

      int action = random.nextInt(PROBABILITY_PRECISION);

      // go to a new page with probability 
      // NEW_PAGE_PROBABILITY / PROBABILITY_PRECISION
      if(action < NEW_PAGE_PROBABILITY) { 
        currentPage = random.nextInt(pages.length); // a random page
        referrer = null;
      }
      else {
        referrer = pages[currentPage];
        action = random.nextInt(linkMatrix[currentPage].length);
        currentPage = linkMatrix[currentPage][action];
      }
    }
    
    connection.commit();
    
  }catch (SQLException ex) {
    connection.rollback();
    throw ex;
  } finally {
    if(statement != null) {
      statement.close();
    }
  }
}
 
Example 19
Project: spr   File: SqlUpdates.java   View Source Code Vote up 4 votes
public static void updateEstructuraFinanciera(
		EstructuraFinanciera estructuraFinancieraObj,
		String usuarioResponsable) {
	try {
		Connection conect = ConnectionConfiguration.conectar();

		String query = "update estructura_financiera set ";
		PreparedStatement update = null;

		if (estructuraFinancieraObj.getEstructura() != 0) {
			query += " estructura = ?, ";
		}
		if (estructuraFinancieraObj.getMes() != 0) {
			query += " mes = ?,";
		}
		if (estructuraFinancieraObj.getProducto() != 0) {
			query += " producto = ?,";
		}
		if (estructuraFinancieraObj.getPlanificado() != 0) {
			query += " planificado = ?, ";
		}
		if (estructuraFinancieraObj.getEjecutado() != 0) {
			query += " ejecutado = ?, ";
		}
		query += " usuario_responsable = ?, ";

		query = query.substring(0, query.length() - 2);
		query += " where id = ?";

		int cantCampos = 0;
		update = conect.prepareStatement(query);
		if (estructuraFinancieraObj.getEstructura() != 0) {
			cantCampos++;
			update.setInt(cantCampos,
					estructuraFinancieraObj.getEstructura());
		}
		if (estructuraFinancieraObj.getMes() != 0) {
			cantCampos++;
			update.setInt(cantCampos, estructuraFinancieraObj.getMes());
		}
		if (estructuraFinancieraObj.getProducto() != 0) {
			cantCampos++;
			update.setInt(cantCampos, estructuraFinancieraObj.getProducto());
		}
		if (estructuraFinancieraObj.getPlanificado() != 0) {
			cantCampos++;
			update.setDouble(cantCampos,
					estructuraFinancieraObj.getPlanificado());
		}
		if (estructuraFinancieraObj.getEjecutado() != 0) {
			cantCampos++;
			update.setDouble(cantCampos,
					estructuraFinancieraObj.getEjecutado());
		}
		cantCampos++;
		update.setString(cantCampos, usuarioResponsable);

		cantCampos++;
		update.setInt(cantCampos, estructuraFinancieraObj.getId());

		update.execute();
		conect.close();
	} catch (SQLException e) {
		e.printStackTrace();
	}

}
 
Example 20
Project: ramus   File: UniversalPersistentFactory.java   View Source Code Vote up 4 votes
public void updateInTransaction(Object object, final boolean cached,
                                Class clazz) throws SQLException {
    PersistentRow row = rowHash.get(clazz);
    PersistentWrapper wrapper = rowWrappers.get(clazz);
    List<PersistentField> fields = row.getFields();

    Object[] objects = new Object[fields.size()];

    StringBuffer set = new StringBuffer("UPDATE " + row.getTableName()
            + " SET ");
    StringBuffer key = new StringBuffer(" WHERE ");

    boolean firstP = true;
    boolean firstS = true;

    int k = 0;

    for (int i = 0; i < objects.length; i++) {
        PersistentField field = fields.get(i);
        if (field.isPrimary()) {
            if (firstP)
                firstP = false;
            else
                key.append(" AND ");
        } else {
            if (firstS)
                firstS = false;
            else
                set.append(", ");
        }
        if (field.isPrimary()) {
            key.append(field.getDatabaseName());
            key.append("=?");
        } else {
            set.append(field.getDatabaseName());
            set.append("=?");
        }
        if (!field.isPrimary()) {
            objects[k] = wrapper.getField(object, field.getName());
            k++;
        }
    }
    for (int i = 0; i < objects.length; i++)
        if (fields.get(i).isPrimary()) {
            objects[k] = wrapper.getField(object, fields.get(i).getName());
            k++;
        }
    String sql = set.toString() + key.toString();
    PreparedStatement ps = template.getPreparedStatement(sql, cached);
    synchronized (ps) {
        template.setParams(ps, objects);
        ps.execute();
        if (!cached)
            ps.close();
    }
}