Example usage for java.sql Connection createStatement

List of usage examples for java.sql Connection createStatement

Introduction

In this page you can find the example usage for java.sql Connection createStatement.

Prototype

Statement createStatement() throws SQLException;

Source Link

Document

Creates a Statement object for sending SQL statements to the database.

Usage

From source file:Main.java

private static List<Person> findAll(Connection conn) throws SQLException {
    List<Person> rows = new ArrayList<Person>();
    Statement stat = conn.createStatement();
    ResultSet rs = stat.executeQuery("select * from people;");
    while (rs.next()) {
        rows.add(new Person(rs.getString("name"), rs.getString("occupation")));
    }//from www. j  a v a2s. c  om
    close(stat);
    close(rs);
    return rows;
}

From source file:TestDebug_MySQL.java

public static int countRows(Connection conn, String tableName) throws SQLException {
    Statement stmt = null;/*from www.ja  v a  2  s.  co m*/
    ResultSet rs = null;
    int rowCount = -1;
    try {
        stmt = conn.createStatement();
        rs = stmt.executeQuery("SELECT COUNT(*) FROM " + tableName);
        // get the number of rows from the result set
        rs.next();
        rowCount = rs.getInt(1);
    } finally {
        rs.close();
        stmt.close();
    }

    return rowCount;
}

From source file:Main.java

/**
 * //from  w w  w  .  ja  v  a 2 s . c o  m
 * @param conn
 * @param table
 * @param c_name
 */
public static void updateContentVersion(Connection conn, String table, String c_name) throws Exception {
    ResultSet rs;
    Statement s;
    int v;

    s = conn.createStatement();
    rs = s.executeQuery("SELECT c_version FROM " + table + " WHERE c_name = '" + c_name + "'");
    v = 1;

    if (rs.next()) {
        v = rs.getInt(1);
        v++;
    }

    rs.close();

    s.executeUpdate("UPDATE " + table + " SET c_version = " + v + " WHERE c_name = '" + c_name + "'");
    s.close();
}

From source file:com.wipro.ats.bdre.clustermigration.SourceStageLoad.java

protected static Connection getHiveJDBCConnection(String dbName, String hiveConnection) throws SQLException {
    try {/*  ww  w .j a  v  a 2s . c om*/
        Class.forName(IMConstant.HIVE_DRIVER_NAME);
        Connection con = DriverManager.getConnection(hiveConnection + "/" + dbName, null, null);
        con.createStatement().execute("set hive.exec.dynamic.partition.mode=nonstrict");
        con.createStatement().execute("set hive.exec.dynamic.partition=true");
        con.createStatement().execute("set hive.exec.max.dynamic.partitions.pernode=1000");
        return con;
    } catch (ClassNotFoundException e) {
        throw new ETLException(e);
    } catch (SQLException e) {
        throw new ETLException(e);
    }
}

From source file:de.unibi.cebitec.bibiserv.util.visualizer.AbstractTest.java

private static DataSource derbydb() throws Exception {

    EmbeddedDataSource ds = new EmbeddedDataSource();

    String db = "test/testdb_" + System.currentTimeMillis();

    // check if database exists
    File db_dir = new File(db);
    if (db_dir.exists()) {
        try {/*from ww w.j  a va 2  s .c  o m*/
            FileUtils.deleteDirectory(db_dir);
        } catch (IOException e) {
            LOG.error(e);
            assertTrue(e.getMessage(), false);
        }
    }
    ds.setDatabaseName(db);
    ds.setCreateDatabase("create");

    Connection con = ds.getConnection();
    Statement stmt = con.createStatement();

    // read SQL Statement from file
    BufferedReader r = new BufferedReader(
            new InputStreamReader(TestRAEDA.class.getResourceAsStream("/status.sql")));
    String line;
    StringBuilder sql = new StringBuilder();
    while ((line = r.readLine()) != null) {
        // skip commend lines
        if (!line.startsWith("--")) {
            sql.append(line);
            sql.append('\n');
        }
    }
    r.close();

    // execute sqlcmd's
    for (String sqlcmd : sql.toString().split(";")) {
        sqlcmd = sqlcmd.trim(); // ignore trailing/ending whitespaces
        sqlcmd = sqlcmd.replaceAll("\n\n", "\n"); // remove double newline
        if (sqlcmd.length() > 1) { // if string contains more than one char, execute sql cmd
            LOG.debug(sqlcmd + "\n");
            stmt.execute(sqlcmd);
        }
    }

    // close stmt
    stmt.close();

    return ds;
}

From source file:com.example.mydtapp.JdbcInputAppTest.java

public static void cleanTable() {
    try {/*from w  w w.j  a v a 2s.  c o  m*/
        Connection con = DriverManager.getConnection(URL);
        Statement stmt = con.createStatement();
        String cleanTable = "delete from " + TABLE_NAME;
        stmt.executeUpdate(cleanTable);
    } catch (SQLException e) {
        throw new RuntimeException(e);
    }
}

From source file:Main.java

/***      Check for  WISH_LIST table    ****/
public static boolean wwdChk4Table(Connection conTst) throws SQLException {
    boolean chk = true;
    boolean doCreate = false;
    try {/*from  w ww.  ja  v  a2s  .c o  m*/
        Statement s = conTst.createStatement();
        s.execute("update WISH_LIST set ENTRY_DATE = CURRENT_TIMESTAMP, WISH_ITEM = 'TEST ENTRY' where 1=3");
    } catch (SQLException sqle) {
        String theError = (sqle).getSQLState();
        //   System.out.println("  Utils GOT:  " + theError);
        /** If table exists will get -  WARNING 02000: No row was found **/
        if (theError.equals("42X05")) // Table does not exist
        {
            return false;
        } else if (theError.equals("42X14") || theError.equals("42821")) {
            System.out.println(
                    "WwdChk4Table: Incorrect table definition. Drop table WISH_LIST and rerun this program");
            throw sqle;
        } else {
            System.out.println("WwdChk4Table: Unhandled SQLException");
            throw sqle;
        }
    }
    //  System.out.println("Just got the warning - table exists OK ");
    return true;
}

From source file:CheckJDBCInstallation_Oracle.java

/**
 * Test Validity of a Connection/*ww w  . j av  a 2  s. c om*/
 * 
 * @param conn
 *          a JDBC connection object
 * @param query
 *          a sql query to test against database connection
 * @return true if a given connection object is a valid one; otherwise return
 *         false.
 */
public static boolean testConnection(Connection conn, String query) {

    ResultSet rs = null;
    Statement stmt = null;
    try {
        stmt = conn.createStatement();
        if (stmt == null) {
            return false;
        }

        rs = stmt.executeQuery(query);
        if (rs == null) {
            return false;
        }

        if (rs.next()) {
            // connection object is valid: we were able to
            // connect to the database and return something useful.
            return true;
        }
        // there is no hope any more for the validity
        // of the connection object
        return false;

    } catch (Exception e) {
        return false;
    } finally {
        // close database resources
        try {
            rs.close();
            stmt.close();
        } catch (Exception e) {
            // ignore
        }
    }
}

From source file:CheckJDBCInstallation.java

/**
 * Test Validity of a Connection//  www . j  a va2 s  .  c  o m
 * 
 * @param conn
 *          a JDBC connection object
 * @param query
 *          a sql query to test against db connection
 * @return true if a given connection object is a valid one; otherwise return
 *         false.
 */
public static boolean testConnection(Connection conn, String query) {
    ResultSet rs = null;
    Statement stmt = null;
    try {
        stmt = conn.createStatement();
        if (stmt == null) {
            return false;
        }

        rs = stmt.executeQuery(query);
        if (rs == null) {
            return false;
        }

        // connection object is valid: you were able to
        // connect to the database and return something useful.
        if (rs.next()) {
            return true;
        }

        // there is no hope any more for the validity
        // of the Connection object
        return false;
    } catch (Exception e) {
        // something went wrong: connection is bad
        return false;
    } finally {
        // close database resources
        try {
            rs.close();
            stmt.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.silverpeas.components.model.AbstractJndiCase.java

public static void executeDDL(IDatabaseConnection databaseConnection, String filename) {
    Connection connection = null;
    try {/*from ww  w. jav a  2 s . c om*/
        connection = databaseConnection.getConnection();
        Statement st = connection.createStatement();
        st.execute(loadDDL(filename));
        connection.commit();
    } catch (Exception e) {
        LoggerFactory.getLogger(AbstractJndiCase.class).error("Error creating tables", e);
    }
}