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

The following are Jave code examples for showing how to use execute() of the java.sql.Statement 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: lams   File: JdbcTemplate.java   View Source Code Vote up 6 votes
@Override
public void execute(final String sql) throws DataAccessException {
	if (logger.isDebugEnabled()) {
		logger.debug("Executing SQL statement [" + sql + "]");
	}
	class ExecuteStatementCallback implements StatementCallback<Object>, SqlProvider {
		@Override
		public Object doInStatement(Statement stmt) throws SQLException {
			stmt.execute(sql);
			return null;
		}
		@Override
		public String getSql() {
			return sql;
		}
	}
	execute(new ExecuteStatementCallback());
}
 
Example 2
Project: SistemaAlmoxarifado   File: RequisicaoDAO.java   View Source Code Vote up 6 votes
public static Requisicao create(Requisicao requisicao) throws SQLException {
    Statement stm
            = Database.createConnection().
                    createStatement();
    String sql
            = "INSERT INTO requisicoes (`servidor`, `data`, `observacao`) VALUES ('"
            + requisicao.getServidor().getId() + "','"
            + requisicao.getData() + "','"
            + requisicao.getObservacao() + "')";

    stm.execute(sql, Statement.RETURN_GENERATED_KEYS);
    ResultSet rs = stm.getGeneratedKeys();
    rs.next();
    requisicao.setId(rs.getInt(1));
    
    if(requisicao.getItens() != null){
        for (RequisicaoProduto item : requisicao.getItens()) {
            item.setRequisicaoId(requisicao.getId());
            RequisicaoProdutoDAO.create(item);
        }
    }
    
    return requisicao;
}
 
Example 3
Project: spr   File: SqlUpdates.java   View Source Code Vote up 6 votes
public static boolean updateBorradoUsuarios(Usuario fundamentacionObj,
		String usuarioResponsable) {
	Connection conect = ConnectionConfiguration.conectar();

	Statement statement = null;
	fundamentacionObj.changeBorrado();

	String query = "update usuario set borrado='"
			+ fundamentacionObj.isBorrado() + "'";
	query += ", usuario_responsable='" + usuarioResponsable + "'";
	query += " where id =" + fundamentacionObj.getId();
	try {
		statement = conect.createStatement();
		statement.execute(query);
		conect.close();
		return true;
	} catch (SQLException e) {
		e.printStackTrace();
		return false;
	}

}
 
Example 4
Project: icewolf   File: IWDatabaseHelper.java   View Source Code Vote up 6 votes
public void updateSetting(String key, String value) {
    connect();
    try {
        Statement statement = connection.createStatement();

        String sql = "UPDATE settings SET \n"
                + "value='" + value + "' WHERE parameterName='" + key + "';";

        statement.execute(sql);
    } catch (SQLException ex) {
        System.err.println("Fatal database problem [updateSetting()]: " + ex.getMessage());
        System.exit(1);
    }

    disconnect();
}
 
Example 5
Project: tcp   File: SqlUpdates.java   View Source Code Vote up 6 votes
public static boolean borradoEvidencia(Evidencia objeto, String usuarioResponsable){
  	 Connection conect=ConnectionConfiguration.conectar();
  	 Statement statement = null;
  	 objeto.changeBorrado();
  	 
	 String query = "update evidencia set borrado='"+objeto.isBorrado()+"'";
	 		query += ", usuario_responsable='" + usuarioResponsable + "'";
	
		 query+=" where id ="+objeto.getId();
	  	
	 try {
		statement=conect.createStatement();
		statement.execute(query);
	    conect.close();
	    return true;
	 }catch (SQLException e) {e.printStackTrace(); return false;}
}
 
Example 6
Project: spr   File: SqlDelete.java   View Source Code Vote up 6 votes
public static void deleteEstrategiaHasObjetivo(String id){
 	 Connection conect=ConnectionConfiguration.conectar();
 	 Statement statement = null;
 String 									query = "delete from estrategia_has_objetivo ";
 //if (id!="")								query+= "id=\""+id+"\", ";
 /*if (estrategia_id!="")						query+= "estrategia_id=\""+estrategia_id+"\", ";
 if (estrategia_eje_estrategico_id!="")		query+= "estrategia_eje_estrategico_id=\""+estrategia_eje_estrategico_id+"\", ";
 if (estrategia_linea_transversal_id!="")	query+= "estrategia_linea_transversal_id=\""+estrategia_linea_transversal_id+"\", ";
 if (objetivo_id!="")						query+= "objetivo_id=\""+objetivo_id+"\", ";
 if (objetivo_tipo_objetivo_id!="")			query+= "objetivo_tipo_objetivo_id=\""+objetivo_tipo_objetivo_id+"\", ";
 if (es_principal!="")						query+= "es_principal=\""+es_principal+"\", ";
 query = query.substring(0, query.length()-2);*/
 query+="where id ="+id;
		
try {
	statement=conect.createStatement();
	statement.execute(query);
    conect.close();
} catch (SQLException e) {e.printStackTrace();}
 }
 
Example 7
Project: sumo   File: SelectableVectorLayer.java   View Source Code Vote up 6 votes
private void buildDatabase(GeometryImage glayer) {
    try {
        Connection conn = DriverManager.getConnection("jdbc:h2:~/.sumo/VectorData;AUTO_SERVER=TRUE", "sa", "");
        Statement stat = conn.createStatement();
        stat.execute("DROP TABLE \"" + glayer.getName() + "\" IF EXISTS");
        String sql = null;
        File tempfile = File.createTempFile(glayer.getName(), ".csv");
        GenericCSVIO.createSimpleCSV(glayer, tempfile.getAbsolutePath(),false);
        sql = "create table \"" + glayer.getName() + "\" as select * from csvread('" + tempfile.getAbsolutePath() + "')";
        stat.execute(sql);
        stat.close();
        conn.close();
    } catch (Exception ex) {
        logger.error(ex.getMessage(),ex);
    }
}
 
Example 8
Project: spr   File: SqlUpdates.java   View Source Code Vote up 6 votes
public static void updateTipoCatalogoDestinatario(String id, String nombre,
		String descripcion) {
	Connection conect = ConnectionConfiguration.conectar();
	Statement statement = null;
	String query = "update tipo_catalogo_destinatario set ";
	// if (id!="") query+= "id=\""+id+"\", ";
	if (nombre != "")
		query += "nombre=\"" + nombre + "\", ";
	if (descripcion != "")
		query += "descripcion=\"" + descripcion + "\", ";
	query = query.substring(0, query.length() - 2);
	query += "where id=" + id;

	try {
		statement = conect.createStatement();
		statement.execute(query);
		conect.close();
	} catch (SQLException e) {
		e.printStackTrace();
	}
}
 
Example 9
Project: tqdev-metrics   File: InstrumentedDataSourceTest.java   View Source Code Vote up 6 votes
/**
 * Should measure statement.
 *
 * @throws SQLException
 *             the SQL exception
 */
@Test
public void shouldMeasureStatement() throws SQLException {
	Statement statements[] = { dataSource.getConnection().createStatement(),
			dataSource.getConnection().createStatement(1, 1), dataSource.getConnection().createStatement(1, 1, 1) };
	for (Statement statement : statements) {
		statement.execute("select");
		statement.execute("select", 1);
		statement.execute("select", new int[] {});
		statement.execute("select", new String[] {});
		statement.executeQuery("select");
		statement.executeUpdate("select");
		statement.executeUpdate("select", 1);
		statement.executeUpdate("select", new int[] {});
		statement.executeUpdate("select", new String[] {});
		statement.executeLargeUpdate("select");
		statement.executeLargeUpdate("select", 1);
		statement.executeLargeUpdate("select", new int[] {});
		statement.executeLargeUpdate("select", new String[] {});
		statement.addBatch("select");
		statement.executeBatch();
		statement.executeLargeBatch();
	}
	assertThat(registry.get("jdbc.Statement.Invocations", "select")).isEqualTo(1L * 15 * statements.length);
	assertThat(registry.get("jdbc.Statement.Durations", "select")).isEqualTo(123456789L * 15 * statements.length);
}
 
Example 10
Project: oscm   File: DatabaseUpgradeHandler.java   View Source Code Vote up 6 votes
/**
 * Sets the specified version information in the version table in the
 * database.
 * 
 * @param conn
 *            The database connection.
 * @param versionInfoToSet
 *            The version information to be set.
 * @throws SQLException
 */
private void setVersionInformation(Connection conn,
        DatabaseVersionInfo versionInfoToSet, long time)
        throws SQLException {
    Statement stmt = conn.createStatement();
    try {
        stmt.execute("DELETE FROM VERSION");
    } finally {
        closeStatement(stmt);
    }

    PreparedStatement pStmt = conn
            .prepareStatement("INSERT INTO VERSION(productMajorVersion, productMinorVersion, schemaVersion, migrationDate) VALUES(?,?,?,?)");
    try {
        pStmt.setInt(1, versionInfoToSet.getProductMajorVersion());
        pStmt.setInt(2, versionInfoToSet.getProductMinorVersion());
        pStmt.setInt(3, versionInfoToSet.getSchemaVersion());
        pStmt.setTimestamp(4, new Timestamp(time));
        pStmt.execute();
    } finally {
        closeStatement(pStmt);
    }
}
 
Example 11
Project: SistemaAlmoxarifado   File: UsuarioDAO.java   View Source Code Vote up 6 votes
public static Usuario create(Usuario usuario) throws SQLException {
    Statement stm
            = Database.createConnection().
                    createStatement();
    String sql
            = "INSERT INTO usuarios (`email`, `senha`, `status`, `admin`, `servidor`) VALUES ('"
            + usuario.getEmail() + "','"
            + usuario.getSenha() + "','"
            + usuario.isAtivo() + "','"
            + usuario.isAdmin() + "','"
            + usuario.getServidor().getId() + "')";

    stm.execute(sql, Statement.RETURN_GENERATED_KEYS);
    ResultSet rs = stm.getGeneratedKeys();
    rs.next();
    usuario.setId(rs.getInt(1));
    return usuario;
}
 
Example 12
Project: spr   File: SqlUpdates.java   View Source Code Vote up 5 votes
public static boolean updateBorradoObjetivosSugeridos(
		ObjetivoSugerido objetivoSugeridoObjeto, String usuarioResponsable)
		throws ParseException {
	Connection conect = ConnectionConfiguration.conectar();
	Statement statement = null;
	objetivoSugeridoObjeto.changeBorrado();

	String query = "update objetivo_sugerido set borrado='"
			+ objetivoSugeridoObjeto.isBorrado() + "', ";
	query += "usuario_responsable='" + usuarioResponsable + "'";

	query += " where objetivo_id ="
			+ objetivoSugeridoObjeto.getObjetivoId()
			+ " and objetivo_tipo_objetivo_id="
			+ objetivoSugeridoObjeto.getTipoObjetivoId()
			+ " and objetivo_anho="
			+ objetivoSugeridoObjeto.getObjetivoAnho()
			+ " and objetivo_version="
			+ objetivoSugeridoObjeto.getObjetivoVersion()
			+ " and objetivo_sugerido_id="
			+ objetivoSugeridoObjeto.getObjetivoSugeridoId()
			+ " and objetivo_sugerido_tipo_id="
			+ objetivoSugeridoObjeto.getObjetivoSugeridoTipoId()
			+ " and objetivo_sugerido_anho="
			+ objetivoSugeridoObjeto.getObjetivoSugeridoAnho()
			+ " and objetivo_sugerido_version="
			+ objetivoSugeridoObjeto.getObjetivoSugeridoVersion();
	try {
		statement = conect.createStatement();
		statement.execute(query);
		conect.close();
		return true;
	} catch (SQLException e) {
		e.printStackTrace();
		return false;
	}
}
 
Example 13
Project: tangyuan2   File: SqlActuator.java   View Source Code Vote up 5 votes
public void run(Connection connection, String sql) throws SQLException {
	Statement stmt = connection.createStatement();
	try {
		stmt.execute(sql);
	} finally {
		try {
			stmt.close();
		} catch (SQLException e) {
			// ignore
		}
	}
}
 
Example 14
Project: parabuild-ci   File: TestCascade.java   View Source Code Vote up 5 votes
private static void createDatabase() throws SQLException {

        new File("testdb.backup").delete();
        new File("testdb.data").delete();
        new File("testdb.properties").delete();
        new File("testdb.script").delete();

        jdbcDataSource dataSource = new jdbcDataSource();

        dataSource.setDatabase("jdbc:hsqldb:testdb");

        Connection con   = dataSource.getConnection("sa", "");
        String[]   saDDL = {
            "CREATE CACHED TABLE XB (EIACODXA VARCHAR(10) NOT NULL, LSACONXB VARCHAR(18) NOT NULL, ALTLCNXB VARCHAR(2) NOT NULL, LCNTYPXB VARCHAR(1) NOT NULL, LCNINDXB VARCHAR(1), LCNAMEXB VARCHAR(19), UPDT_BY VARCHAR(32), LST_UPDT TIMESTAMP, CONSTRAINT XPKXB PRIMARY KEY (EIACODXA, LSACONXB, ALTLCNXB, LCNTYPXB));",

//            "CREATE INDEX XIF2XB ON XB (EIACODXA);",
            "CREATE CACHED TABLE CA ( EIACODXA VARCHAR(10) NOT NULL, LSACONXB VARCHAR(18) NOT NULL, ALTLCNXB VARCHAR(2) NOT NULL, LCNTYPXB VARCHAR(1) NOT NULL, TASKCDCA VARCHAR(7) NOT NULL, TSKFRQCA NUMERIC(7,4), UPDT_BY VARCHAR(32), LST_UPDT TIMESTAMP, CONSTRAINT XPKCA PRIMARY KEY (EIACODXA, LSACONXB, ALTLCNXB, LCNTYPXB, TASKCDCA),        CONSTRAINT R_XB_CA FOREIGN KEY (EIACODXA, LSACONXB, ALTLCNXB, LCNTYPXB) REFERENCES XB ON DELETE CASCADE);",

//            "CREATE INDEX XIF26CA ON CA ( EIACODXA, LSACONXB, ALTLCNXB, LCNTYPXB);"
        };
        Statement stmt = con.createStatement();

        for (int index = 0; index < saDDL.length; index++) {
            stmt.executeUpdate(saDDL[index]);
        }

        stmt.execute("SHUTDOWN");
        con.close();
    }
 
Example 15
Project: lams   File: AbstractEmbeddedDatabaseConfigurer.java   View Source Code Vote up 5 votes
@Override
public void shutdown(DataSource dataSource, String databaseName) {
	try {
		Connection connection = dataSource.getConnection();
		Statement stmt = connection.createStatement();
		stmt.execute("SHUTDOWN");
	}
	catch (SQLException ex) {
		if (logger.isWarnEnabled()) {
			logger.warn("Could not shutdown embedded database", ex);
		}
	}
}
 
Example 16
Project: SistemaAlmoxarifado   File: TipoDAO.java   View Source Code Vote up 5 votes
public static Tipo create(Tipo tipo) throws SQLException {
    Statement stm
            = Database.createConnection().
                    createStatement();
    String sql
            = "INSERT INTO tipos (`tipo`) VALUES ('"
            + tipo.getTipo() + "')";

    stm.execute(sql, Statement.RETURN_GENERATED_KEYS);
    ResultSet rs = stm.getGeneratedKeys();
    rs.next();
    tipo.setId(rs.getInt(1));
    return tipo;
}
 
Example 17
Project: Transwarp-Sample-Code   File: Executor.java   View Source Code Vote up 5 votes
/**
 * 创建Hyperbase表
 * @param connection JDBC连接
 */
public static void createHBaseTable(Connection connection) {
    try {
        Statement statement = connection.createStatement();
        String sql1 = Constant.PARAMETER;
        statement.execute(sql1);
        String sql2 = Constant.CREATE_EXTERNAL_TABLE;
        statement.execute(sql2);
        statement.close();
    } catch (SQLException e) {
        e.printStackTrace();
    }
}
 
Example 18
Project: OpenDiabetes   File: DatabaseManagerCommon.java   View Source Code Vote up 5 votes
static void createTestTables(Statement sStatement) {

        String[] demo = {
            "DROP TABLE Item IF EXISTS;", "DROP TABLE Invoice IF EXISTS;",
            "DROP TABLE Product IF EXISTS;", "DROP TABLE Customer IF EXISTS;",
            "CREATE TABLE Customer(ID INTEGER PRIMARY KEY,FirstName VARCHAR(20),"
            + "LastName VARCHAR(20),Street VARCHAR(20),City VARCHAR(20));",
            "CREATE TABLE Product(ID INTEGER PRIMARY KEY,Name VARCHAR(20),"
            + "Price DECIMAL(10,2));",
            "CREATE TABLE Invoice(ID INTEGER PRIMARY KEY,CustomerID INTEGER,"
            + "Total DECIMAL(10,2), FOREIGN KEY (CustomerId) "
            + "REFERENCES Customer(ID) ON DELETE CASCADE);",
            "CREATE TABLE Item(InvoiceID INTEGER,Item INTEGER,"
            + "ProductID INTEGER,Quantity INTEGER,Cost DECIMAL(10,2),"
            + "PRIMARY KEY(InvoiceID,Item), "
            + "FOREIGN KEY (InvoiceId) REFERENCES "
            + "Invoice (ID) ON DELETE CASCADE, FOREIGN KEY (ProductId) "
            + "REFERENCES Product(ID) ON DELETE CASCADE);"
        };

        for (int i = 0; i < demo.length; i++) {

            // drop table may fail
            try {
                sStatement.execute(demo[i]);
            } catch (SQLException e) {
                ;
            }
        }
    }
 
Example 19
Project: parabuild-ci   File: FindFile.java   View Source Code Vote up 5 votes
/**
 * Method declaration
 *
 *
 * @param conn
 * @param root
 *
 * @throws SQLException
 */
static void fillFileNames(Connection conn,
                          String root) throws SQLException {

    System.out.println("Re-creating the database...");

    // Create a statement object
    Statement stat = conn.createStatement();

    // Try to drop the table
    try {
        stat.executeUpdate("DROP TABLE Files");
    } catch (SQLException e) {    // Ignore Exception, because the table may not yet exist
    }

    // For compatibility to other database, use varchar(255)
    // In HSQL Database Engine, length is unlimited, like Java Strings
    stat.execute("CREATE TABLE Files"
                 + "(Path varchar(255),Name varchar(255))");

    // Close the Statement object, it is no longer used
    stat.close();

    // Use a PreparedStatement because Path and Name could contain '
    PreparedStatement prep =
        conn.prepareCall("INSERT INTO Files (Path,Name) VALUES (?,?)");

    // Start with the 'root' directory and recurse all subdirectories
    fillPath(root, "", prep);

    // Close the PreparedStatement
    prep.close();
    System.out.println("Finished");
}
 
Example 20
Project: gretl   File: CsvImportTest.java   View Source Code Vote up 4 votes
@Test
public void importOk() throws Exception {
    String schemaName = "csvimport".toLowerCase();
    Connection con = null;
    try{
        con = TestUtilSql.connectPG();
        TestUtilSql.createOrReplaceSchema(con, schemaName);
        Statement s1 = con.createStatement();
        s1.execute("CREATE TABLE "+schemaName+".importdata(t_id serial, \"Aint\" integer, adec decimal(7,1), atext varchar(40), aenum varchar(120),adate date, atimestamp timestamp, aboolean boolean, aextra varchar(40))");
        s1.close();
        TestUtilSql.grantDataModsInSchemaToUser(con, schemaName, TestUtilSql.PG_CON_DMLUSER);

        con.commit();
        TestUtilSql.closeCon(con);

        GradleVariable[] gvs = {GradleVariable.newGradleProperty(TestUtilSql.VARNAME_PG_CON_URI, TestUtilSql.PG_CON_URI)};
        TestUtil.runJob("jobs/CsvImport", gvs);

        //reconnect to check results
        con = TestUtilSql.connectPG();

        Statement s2 = con.createStatement();
        ResultSet rs=s2.executeQuery("SELECT \"Aint\" , adec, atext, aenum,adate, atimestamp, aboolean, aextra FROM "+schemaName+".importdata WHERE t_id=1"); 
        if(!rs.next()) {
            fail();
        }
        assertEquals(2,rs.getInt(1));
        assertEquals(new BigDecimal("3.1"),rs.getBigDecimal(2));
        assertEquals("abc",rs.getString(3));
        assertEquals("rot",rs.getString(4));
        assertEquals(new java.sql.Date(2017-1900,9-1,21),rs.getDate(5));
        assertEquals(new java.sql.Timestamp(2016-1900,8-1,22,13,15,22,450000000),rs.getTimestamp(6));
        assertEquals(true,rs.getBoolean(7));
        if(rs.next()) {
            fail();
        }
        rs.close();
        s1.close();
    }
    finally {
        TestUtilSql.closeCon(con);
    }
}