Example usage for java.sql Statement execute

List of usage examples for java.sql Statement execute

Introduction

In this page you can find the example usage for java.sql Statement execute.

Prototype

boolean execute(String sql) throws SQLException;

Source Link

Document

Executes the given SQL statement, which may return multiple results.

Usage

From source file:com.micromux.cassandra.jdbc.MetadataResultSetsTest.java

@BeforeClass
public static void setUpBeforeClass() throws Exception {

    // configure OPTIONS
    if (!StringUtils.isEmpty(TRUST_STORE)) {
        OPTIONS = String.format("trustStore=%s&trustPass=%s", URLEncoder.encode(TRUST_STORE), TRUST_PASS);
    }/*  w w  w . j a  v a 2  s  .  com*/

    Class.forName("com.micromux.cassandra.jdbc.CassandraDriver");
    String URL = String.format("jdbc:cassandra://%s:%d/%s?version=3.0.0&%s", HOST, PORT, "system", OPTIONS);
    System.out.println("Connection URL = '" + URL + "'");

    con = DriverManager.getConnection(URL);
    Statement stmt = con.createStatement();

    // Drop Keyspace
    String dropKS1 = String.format(DROP_KS, KEYSPACE1);
    String dropKS2 = String.format(DROP_KS, KEYSPACE2);

    try {
        stmt.execute(dropKS1);
        stmt.execute(dropKS2);
    } catch (Exception e) {
        /* Exception on DROP is OK */}

    // Create KeySpace
    String createKS1 = String.format(CREATE_KS, KEYSPACE1);
    String createKS2 = String.format(CREATE_KS, KEYSPACE2);
    stmt = con.createStatement();
    stmt.execute("USE system;");
    stmt.execute(createKS1);
    stmt.execute(createKS2);

    // Use Keyspace
    String useKS1 = String.format("USE \"%s\";", KEYSPACE1);
    String useKS2 = String.format("USE \"%s\";", KEYSPACE2);
    stmt.execute(useKS1);

    // Create the target Column family
    String createCF1 = "CREATE COLUMNFAMILY test1 (keyname text PRIMARY KEY," + " t1bValue boolean,"
            + " t1iValue int" + ") WITH comment = 'first TABLE in the Keyspace'" + ";";

    String createCF2 = "CREATE COLUMNFAMILY test2 (keyname text PRIMARY KEY," + " t2bValue boolean,"
            + " t2iValue int" + ") WITH comment = 'second TABLE in the Keyspace'" + ";";

    stmt.execute(createCF1);
    stmt.execute(createCF2);
    stmt.execute(useKS2);
    stmt.execute(createCF1);
    stmt.execute(createCF2);

    stmt.close();
    con.close();

    // open it up again to see the new CF
    con = DriverManager.getConnection(
            String.format("jdbc:cassandra://%s:%d/%s?version=3.0.0&%s", HOST, PORT, KEYSPACE1, OPTIONS));

}

From source file:io.agi.framework.persistence.jdbc.JdbcUtil.java

/**
 * Execute an INSERT or UPDATE statement, that doesn't return any data.
 *
 * @param dbUrl//from  w ww  .ja va2  s.  c o m
 * @param user
 * @param password
 * @param sql
 */
public static void Execute(String dbUrl, String user, String password, String sql) {
    Connection c = null;
    Statement s = null;
    try {
        c = DriverManager.getConnection(dbUrl, user, password);

        //STEP 4: Execute a query
        //_logger.info( "JDBC T: {} @1 jdbc = {}", System.currentTimeMillis(), sql );
        s = c.createStatement();
        //_logger.info( "JDBC T: {} @2 ", System.currentTimeMillis() );
        s.execute(sql);
        //_logger.info( "JDBC T: {} @3 ", System.currentTimeMillis() );

        //STEP 6: Clean-up environment
        //            s.close();
        //            c.close();
    } catch (SQLException se) {
        logger.error(se.toString(), se);
    } catch (Exception e) {
        logger.error(s.toString(), s);
    } finally {
        try {
            if (s != null)
                s.close();
        } catch (SQLException se2) {
            logger.error(se2.toString(), se2);
        } finally {
            try {
                if (c != null)
                    c.close();
            } catch (SQLException se) {
                logger.error(se.toString(), se);
            }
        }
    }
}

From source file:com.splicemachine.homeless.TestUtils.java

public static void executeSql(Connection connection, String sqlStatements, String schema) {
    try {// w w  w  .  ja v  a 2s  . c o m
        String str = sqlStatements.replaceAll("<SCHEMA>", schema);
        str = str.replaceAll("<DIR>", SpliceUnitTest.getResourceDirectory());
        for (String s : str.split(";")) {
            String trimmed = s.trim();
            if (!trimmed.equals("")) {
                Statement stmt = connection.createStatement();
                stmt.execute(s);
                connection.commit();
            }
        }
    } catch (Exception e) {
        throw new RuntimeException("Error running SQL statements: " + sqlStatements, e);
    }
}

From source file:net.antidot.sql.model.core.SQLConnector.java

/**
 * Drop all tables from database with connection c. Specific to MySQL
 * databases./* ww w.  j  a v a  2 s  .c o  m*/
 * 
 * @param c
 * @param driver 
 * @throws SQLException
 */
public static void resetMySQLDatabase(Connection c, DriverType driver) throws SQLException {
    // Get tables of database
    DatabaseMetaData meta = c.getMetaData();
    ResultSet tablesSet = meta.getTables(c.getCatalog(), null, "%", null);
    while (tablesSet.next()) {
        // Extract table name
        String tableName = new String(tablesSet.getString("TABLE_NAME"));
        String tableType = tablesSet.getString("TABLE_TYPE");
        // Get a statement from the connection
        Statement stmt = c.createStatement();
        // Execute the query
        if (driver == DriverType.MysqlDriver) {
            // MySQL compatibility
            stmt.execute("SET FOREIGN_KEY_CHECKS = 0");
            stmt.execute("DROP TABLE \"" + tableName + "\"");
        } else {
            if (tableType != null && tableType.equals("TABLE"))
                stmt.execute("DROP TABLE \"" + tableName + "\" CASCADE");
        }
        stmt.close();
    }
}

From source file:com.floreantpos.util.DatabaseUtil.java

private static void dropModifiedTimeColumn() throws SQLException {
    GenericDAO dao = new GenericDAO();
    Session session = null;//w ww  . ja  v a  2s .c  o  m

    try {
        session = dao.createNewSession();
        Connection connection = session.connection();
        String[] tables = { "CUSTOMER", "GRATUITY", "INVENTORY_GROUP", "INVENTORY_ITEM", "INVENTORY_LOCATION",
                "INVENTORY_META_CODE", "INVENTORY_TRANSACTION", "INVENTORY_TRANSACTION_TYPE", "INVENTORY_UNIT",
                "INVENTORY_VENDOR", "INVENTORY_WAREHOUSE", "KITCHEN_TICKET", "KITCHEN_TICKET_ITEM",
                "MENUITEM_MODIFIERGROUP", "MENU_CATEGORY", "MENU_GROUP", "MENU_ITEM", "MENU_MODIFIER",
                "MENU_MODIFIER_GROUP", "PURCHASE_ORDER", "TAX", "TERMINAL", "TICKET",
                "TICKETITEM_MODIFIERGROUP", "TICKET_ITEM", "TICKETITEM_DISCOUNT", "TRANSACTIONS", "USERS",
                "ZIP_CODE_VS_DELIVERY_CHARGE" };

        for (String table : tables) {
            try {
                Statement statement = connection.createStatement();
                statement.execute("ALTER TABLE " + table + " DROP COLUMN MODIFIED_TIME");
            } catch (Exception e) {
                //logger.error(e);
            }
        }
        connection.commit();
    } finally {
        dao.closeSession(session);
    }
}

From source file:com.hangum.tadpole.engine.sql.util.OracleObjectCompileUtils.java

public static String viewCompile(TableDAO viewDao, UserDBDAO userDB) throws Exception {
    String sqlQuery = "ALTER VIEW " + viewDao.getFullName() + " COMPILE "; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$

    java.sql.Connection javaConn = null;
    Statement statement = null;
    ResultSet rs = null;/*from w ww.j a  v a2s  . c  o  m*/
    try {
        SqlMapClient client = TadpoleSQLManager.getInstance(userDB);
        javaConn = client.getDataSource().getConnection();

        statement = javaConn.createStatement();
        statement.execute(sqlQuery);
        //? all_errors syscat ? . sys.all_errors, syscat.all_errors  ??  ? ? ? . 
        sqlQuery = "Select * From all_Errors where owner = '" + viewDao.getSchema_name() + "' and name='" //$NON-NLS-1$//$NON-NLS-2$
                + viewDao.getName() + "' and type = 'VIEW' order by type, sequence ";
        rs = statement.executeQuery(sqlQuery);

        StringBuffer result = new StringBuffer();
        while (rs.next()) {
            result.append(prettyMsg(rs.getString("line"), rs.getString("position"), rs.getString("text"))); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
        }

        return result.toString();
    } finally {
        try {
            rs.close();
        } catch (Exception e) {
        }
        try {
            statement.close();
        } catch (Exception e) {
        }
        try {
            javaConn.close();
        } catch (Exception e) {
        }
    }
}

From source file:com.hangum.tadpole.engine.sql.util.OracleObjectCompileUtils.java

/**
 * other object compile//from   ww w .j av  a2 s  . c o m
 * 
 * @param actionType 
 * @param objType
 * @param objName
 * @param userDB
 */
public static String otherObjectCompile(PublicTadpoleDefine.QUERY_DDL_TYPE actionType, String objType,
        Map<String, String> paramMap, UserDBDAO userDB, boolean isDebug) throws Exception {
    String withDebugOption = "";
    if (isDebug)
        withDebugOption = "DEBUG";

    String sqlQuery = "ALTER " + objType + " " + paramMap.get("full_name") + " COMPILE " + withDebugOption; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$

    java.sql.Connection javaConn = null;
    Statement statement = null;
    ResultSet rs = null;
    try {
        SqlMapClient client = TadpoleSQLManager.getInstance(userDB);
        javaConn = client.getDataSource().getConnection();

        statement = javaConn.createStatement();
        statement.execute(sqlQuery);

        sqlQuery = "Select * From all_Errors where owner = nvl('" + paramMap.get("schema_name") //$NON-NLS-1$//$NON-NLS-2$
                + "', user) and name='" + paramMap.get("object_name") + "' and type = '" + objType //$NON-NLS-1$
                + "' order by type, sequence ";
        rs = statement.executeQuery(sqlQuery);
        StringBuffer result = new StringBuffer();
        while (rs.next()) {
            result.append(prettyMsg(rs.getString("line"), rs.getString("position"), rs.getString("text"))); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
        }

        return result.toString();
    } finally {
        try {
            rs.close();
        } catch (Exception e) {
        }
        try {
            statement.close();
        } catch (Exception e) {
        }
        try {
            javaConn.close();
        } catch (Exception e) {
        }
    }
}

From source file:com.hangum.tadpole.engine.sql.util.OracleObjectCompileUtils.java

/**
 * package compile//www  .  java 2 s  .c  o m
 * 
 * @param objectName
 * @param userDB
 */
public static String packageCompile(ProcedureFunctionDAO packageDao, UserDBDAO userDB, boolean isDebug)
        throws Exception {
    String withDebugOption = "";
    if (isDebug)
        withDebugOption = "DEBUG";

    String sqlQuery = "ALTER PACKAGE " + packageDao.getFullName(true/*isPackage*/) + " COMPILE " //$NON-NLS-1$//$NON-NLS-2$
            + withDebugOption + " SPECIFICATION "; //$NON-NLS-1$
    String sqlBodyQuery = "ALTER PACKAGE " + packageDao.getFullName(true/*isPackage*/) + " COMPILE " //$NON-NLS-1$//$NON-NLS-2$
            + withDebugOption + " BODY "; //$NON-NLS-1$

    java.sql.Connection javaConn = null;
    Statement statement = null;
    ResultSet rs = null;
    try {
        SqlMapClient client = TadpoleSQLManager.getInstance(userDB);
        javaConn = client.getDataSource().getConnection();

        statement = javaConn.createStatement();
        statement.execute(sqlQuery);
        statement.execute(sqlBodyQuery);

        sqlQuery = "Select * From all_Errors where owner = nvl('" + packageDao.getSchema_name() //$NON-NLS-1$
                + "', user) and name='" + packageDao.getName() //$NON-NLS-1$
                + "' and type in ('PACKAGE', 'PACKAGE BODY') order by type, sequence ";
        rs = statement.executeQuery(sqlQuery);
        StringBuffer result = new StringBuffer();
        while (rs.next()) {
            result.append(prettyMsg(rs.getString("line"), rs.getString("position"), rs.getString("text"))); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ 
        }
        return result.toString();
    } finally {
        try {
            rs.close();
        } catch (Exception e) {
        }
        try {
            statement.close();
        } catch (Exception e) {
        }
        try {
            javaConn.close();
        } catch (Exception e) {
        }

    }
}

From source file:jp.co.acroquest.endosnipe.data.dao.AbstractDao.java

/**
 * ??? CHECK ???/*from   w  w  w  .ja v a  2 s .  c  om*/
 *
 * @param database ??
 * @param tableName ???????
 * @param tableIndex 
 * @param column ????
 * @param year 
 * @throws SQLException SQL ?????
 */
protected static void alterCheckConstraint(final String database, final String tableName, final int tableIndex,
        final String column, final int year) throws SQLException {
    Connection conn = null;
    Statement stmt = null;

    String checkConstraintName = DBInitializer.createCheckConstraintName(tableName, column);

    try {
        conn = getConnection(database);
        stmt = conn.createStatement();

        // CHECK?
        String sqlToDropCheck = "ALTER TABLE " + tableName + " DROP CONSTRAINT " + checkConstraintName
                + " RESTRICT";
        stmt.execute(sqlToDropCheck);

        // CHECK?
        String checkConstraint = DBInitializer.createCheckConstraintText(column, tableIndex, year);
        String sqlToCreateCheck = String.format("ALTER TABLE %s ADD CONSTRAINT %s %s", tableName,
                checkConstraintName, checkConstraint);
        stmt.execute(sqlToCreateCheck);
    } finally {
        SQLUtil.closeStatement(stmt);
        SQLUtil.closeConnection(conn);
    }
}

From source file:database.HashTablesTools.java

private static void dropTable(Connection connection, String tableName) {
    try {//  w  w  w  .  j  a v a 2s .  com
        Statement stmt = connection.createStatement();
        String sql = "DROP TABLE " + tableName;
        stmt.execute(sql);
        System.out.println("Drop table from myDB " + tableName + " !");
        stmt.close();
    } catch (SQLException e1) {
        System.out.println("Table " + tableName + " is not existing so cannot be droped");
    }
}