Example usage for org.springframework.jdbc.core JdbcTemplate JdbcTemplate

List of usage examples for org.springframework.jdbc.core JdbcTemplate JdbcTemplate

Introduction

In this page you can find the example usage for org.springframework.jdbc.core JdbcTemplate JdbcTemplate.

Prototype

public JdbcTemplate(DataSource dataSource) 

Source Link

Document

Construct a new JdbcTemplate, given a DataSource to obtain connections from.

Usage

From source file:com.javacreed.examples.spring.CreateBigTable.java

public static void main(final String[] args) throws Exception {

    final ComboPooledDataSource ds = DbUtils.createDs();
    try {//ww  w  . jav  a2 s .  c  om
        final JdbcTemplate jdbcTemplate = new JdbcTemplate(ds);

        CreateBigTable.LOGGER.debug("Dropping table (if exists)");
        jdbcTemplate.update("DROP TABLE IF EXISTS `big_table`");

        CreateBigTable.LOGGER.debug("Creating table");
        jdbcTemplate.update("CREATE TABLE `big_table`(`id` INT(20), `name` VARCHAR(128))");

        CreateBigTable.LOGGER.debug("Adding records");
        final StringBuilder query = new StringBuilder();
        for (int i = 0, b = 1; i < 1000000; i++) {
            if (i % 500 == 0) {
                if (i > 0) {
                    CreateBigTable.LOGGER.debug("Adding records (batch {})", b++);
                    jdbcTemplate.update(query.toString());
                    query.setLength(0);
                }

                query.append("INSERT INTO `big_table` (`id`, `name`) VALUES ");
            } else {
                query.append(",");
            }

            query.append("  (" + (i + 1) + ", 'Pack my box with five dozen liquor jugs.')");
        }

        CreateBigTable.LOGGER.debug("Adding last batch");
        jdbcTemplate.update(query.toString());
    } finally {
        DbUtils.closeQuietly(ds);
    }

    CreateBigTable.LOGGER.debug("Done");
}

From source file:flywayspike.Main.java

/**
 * Runs the sample./*from   w  ww  .  java2s.  c o  m*/
 *
 * @param args None supported.
 */
public static void main(String[] args) throws Exception {
    DataSource dataSource = new SimpleDriverDataSource(new org.hsqldb.jdbcDriver(),
            "jdbc:hsqldb:file:db/flyway_sample;shutdown=true", "SA", "");
    Flyway flyway = new Flyway();
    flyway.setDataSource(dataSource);
    flyway.setLocations("flywayspike.migration", "abcd");
    flyway.clean();

    System.out.println("Started Migration");
    flyway.migrate();
    JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
    List<Map<String, Object>> results = jdbcTemplate.queryForList("select name from test_user");
    for (Map<String, Object> result : results) {
        System.out.println("Name: " + result.get("NAME"));
    }

    SqlRowSet rowSet = jdbcTemplate.queryForRowSet("select * from schema_version");
    while (rowSet.next()) {
        System.out.print(rowSet.getObject(1));
        System.out.println("  " + rowSet.getObject(2));
    }
}

From source file:io.github.benas.jql.shell.Shell.java

public static void main(String[] args) {
    String databaseFile = "";
    if (args.length >= 1) {
        databaseFile = args[0];//from  ww w  .ja  v a  2 s. c om
    }

    DataSource dataSource = getDataSourceFrom(databaseFile);
    JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
    resultSetExtractor = new StringResultSetExtractor();
    queryExecutor = new QueryExecutor(jdbcTemplate);

    Console console = getConsole();

    String command;
    while (true) {
        System.out.print("$>");
        command = console.readLine();
        if (command.equalsIgnoreCase("quit")) {
            break;
        }
        process(command);
    }
    System.out.println("bye!");
}

From source file:com.javacreed.examples.spring.Example1.java

public static void main(final String[] args) throws Exception {
    final ComboPooledDataSource ds = DbUtils.createDs();
    try {/*  w  w w  .j ava 2  s .  c o m*/
        final JdbcTemplate jdbcTemplate = new JdbcTemplate(ds);

        Example1.LOGGER.debug("Reading all rows");
        final List<Data> rows = jdbcTemplate.query("SELECT * FROM `big_table`", Data.ROW_MAPPER);

        Example1.LOGGER.debug("All records read ({} records)", rows.size());

        // Sleep a bit so that it shows better on the profiler
        TimeUnit.SECONDS.sleep(10);
    } finally {
        DbUtils.closeQuietly(ds);
    }
    Example1.LOGGER.debug("Done");
}

From source file:com.javacreed.examples.spring.Example2.java

public static void main(final String[] args) throws Exception {
    final ComboPooledDataSource ds = DbUtils.createDs();
    try {/*w w  w. ja  v a  2 s.c  o m*/
        final JdbcTemplate jdbcTemplate = new JdbcTemplate(ds);

        Example2.LOGGER.debug("Reading all rows");
        final List<Data> rows = jdbcTemplate.query(new StreamingStatementCreator("SELECT * FROM `big_table`"),
                Data.ROW_MAPPER);

        Example2.LOGGER.debug("All records read ({} records)", rows.size());

        // Sleep a bit so that it shows better on the profiler
        TimeUnit.SECONDS.sleep(10);
    } finally {
        DbUtils.closeQuietly(ds);
    }
    Example2.LOGGER.debug("Done");
}

From source file:com.stehno.sanctuary.core.Sanctuary.java

public static void main(String[] args) throws Exception {
    log.info("Starting run...");

    JdbcTemplate jdbcTemplate = new JdbcTemplate(createDataSource());

    // FIXME: AndroidLocalStore
    LocalStore localStore = new JdbcLocalStore(jdbcTemplate);
    localStore.init();//from w  w  w  .jav  a2s  . c om

    // FIXME: FileSystemRemoteStore, S3RemoteStore, AndroidS3LocalStore?
    // FIXME: remote keys
    RemoteStore remoteStore = new S3RemoteStore("yourkey", "yourotherkey");
    remoteStore.init();

    DirectoryScanner scanner = new DefaultDirectoryScanner(localStore);

    ExecutorService executor = new ThreadPoolExecutor(2, 2, 1, TimeUnit.MINUTES,
            new LinkedBlockingQueue<Runnable>());
    FileArchiver archiver = new DefaultFileArchiver(executor, localStore, remoteStore);

    ChangeSet changeSet = scanner.scanDirectory(WORKING_DIR);

    // FIXME: allow review of changeset here (confirm/cancel)
    log.info("Changes: " + changeSet);

    MessageSet messageSet = archiver.archiveChanges(changeSet);

    // FIXME: allow review of messages here
    log.info("Messages" + messageSet);

    remoteStore.destroy();
    localStore.destroy();
}

From source file:com.kaidad.utilities.MBTilesBase64Converter.java

public static void main(String... args) throws SQLException {
    if (args.length != 1) {
        System.out.println("Usage: MBTilesBase64Converter /path/to/file.mbtiles");
        System.exit(1);//from  w  ww  .  j a  v  a 2  s .c  om
    }
    Connection c = null;
    try {
        c = connectToDb(args[0]);
        //        Statement st = c.createStatement();
        //        ResultSet rs = st.executeQuery("SELECT type, name, tbl_name FROM sqlite_master WHERE type='table'");
        //        while(rs.next()) {
        //            System.out.println("type: " + rs.getString(1) + ", name: " + rs.getString(2) + ", tbl_name: " + rs.getString(3));
        //        }
        JdbcTemplate template = new JdbcTemplate(new SingleConnectionDataSource(c, true));
        executeConversion(template);
        c.commit();
    } finally {
        if (c != null) {
            c.close();
        }
    }
}

From source file:org.jooq.java8.goodies.sql.SQLGoodies.java

public static void main(String[] args) throws Exception {

    Class.forName("org.h2.Driver");
    try (Connection c = getConnection("jdbc:h2:~/test", "sa", "")) {
        String sql = "select schema_name, is_default from information_schema.schemata order by schema_name";

        System.out.println("Fetching data into a with JDBC / Java 7 syntax");
        System.out.println("----------------------------------------------");
        try (PreparedStatement stmt = c.prepareStatement(sql); ResultSet rs = stmt.executeQuery()) {

            while (rs.next()) {
                System.out.println(new Schema(rs.getString("SCHEMA_NAME"), rs.getBoolean("IS_DEFAULT")));
            }/*w w w.  j a  v  a 2  s  .  c  om*/
        }

        System.out.println();
        System.out.println("Fetching data into a lambda expression with jOOQ");
        System.out.println("------------------------------------------------");
        DSL.using(c).fetch(sql)
                .map(r -> new Schema(r.getValue("SCHEMA_NAME", String.class),
                        r.getValue("IS_DEFAULT", boolean.class)))
                // could also be written as
                // .into(Schema.class)
                .forEach(System.out::println);

        System.out.println();
        System.out.println("Fetching data into a lambda expression with Spring JDBC");
        System.out.println("-------------------------------------------------------");
        new JdbcTemplate(new SingleConnectionDataSource(c, true))
                .query(sql,
                        (rs, rowNum) -> new Schema(rs.getString("SCHEMA_NAME"), rs.getBoolean("IS_DEFAULT")))
                .forEach(System.out::println);

        System.out.println();
        System.out.println("Fetching data into a lambda expression with Apache DbUtils");
        System.out.println("-------------------------------------------------------");
        new QueryRunner().query(c, sql, new ArrayListHandler()).stream()
                .map(array -> new Schema((String) array[0], (Boolean) array[1])).forEach(System.out::println);
    }
}

From source file:com.xyxy.platform.modules.core.test.data.DataFixtures.java

public static void executeScript(DataSource dataSource, String... sqlResourcePaths) throws DataAccessException {
    JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
    for (String sqlResourcePath : sqlResourcePaths) {
        Resource resource = resourceLoader.getResource(sqlResourcePath);
        JdbcTestUtils.executeSqlScript(jdbcTemplate, new EncodedResource(resource, DEFAULT_ENCODING), true);
    }/*  w w w . ja v a 2 s  .  co m*/
}

From source file:com.charandeepmatta.database.di.Schema.java

public static void createDatabase(final DataSource dataSource) throws IOException {
    JdbcTemplate jdbc = new JdbcTemplate(dataSource);
    updateSqlFromFile(jdbc, "base.sql");
    PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    Integer i = 0;/*from   www. jav  a 2 s .  com*/
    while (true) {
        i++;
        Resource[] resources = resolver.getResources("classpath*:" + leftPad(i.toString(), 3, "0") + "_*.sql");
        if (resources.length == 0) {
            break;
        }
        updateSqlTo(jdbc, resources[0].getInputStream());
    }
}