Java SQL Table createTableAndInsertData(Connection c)

Here you can find the source of createTableAndInsertData(Connection c)

Description

create Table And Insert Data

License

Open Source License

Declaration

public static void createTableAndInsertData(Connection c) throws SQLException 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class Main {
    private static final int NB_BENCHMARK_OBJECT = 1000;
    public static final String TEST_SMALL_BENCHMARK_OBJECT = "TEST_SMALL_BENCHMARK_OBJECT";

    public static void createTableAndInsertData(Connection c) throws SQLException {
        c.setReadOnly(false);//from w  w  w  .j a  v  a2 s.  c o m
        Statement st = c.createStatement();

        try {
            try {
                ResultSet rs = st.executeQuery("select count(*) from " + TEST_SMALL_BENCHMARK_OBJECT);
                rs.next();
                if (rs.getLong(1) == NB_BENCHMARK_OBJECT) {
                    return;
                } else {
                    st.execute("delete from " + TEST_SMALL_BENCHMARK_OBJECT);
                }
            } catch (Exception e) {
                // ignore
                createSmallBenchmarkObject(st);
            }

            PreparedStatement ps = c
                    .prepareStatement("insert into " + TEST_SMALL_BENCHMARK_OBJECT + " values(?, ?, ?, ?)");
            for (int i = 0; i < NB_BENCHMARK_OBJECT; i++) {
                ps.setLong(1, i);
                ps.setString(2, "name " + i);
                ps.setString(3, "name" + i + "@gmail.com");
                ps.setInt(4, 2000 + (i % 14));
                ps.addBatch();

            }

            ps.executeBatch();

        } finally {
            st.close();
            c.setReadOnly(true);
        }
    }

    public static void createSmallBenchmarkObject(Statement st) throws SQLException {
        st.execute("create table " + TEST_SMALL_BENCHMARK_OBJECT + "(" + " id bigint not null primary key,"
                + " name varchar(100), " + " email varchar(100)," + " year_started int  )");
    }
}

Related

  1. createHSQLTables(LineNumberReader reader, Statement statement)
  2. createSourceTable(Connection con)
  3. createTable(Connection dbCon, String tableName, String fields)
  4. createTable(Statement statement, String spaceName, String minSeeders, String capacity, String replicationCount)
  5. createTable(String createTblSql, Connection conn)
  6. dropTable(String tableName, Connection con)
  7. dumpTable(Connection conn, String TableName, PrintWriter out)
  8. dumpTable(Connection connection, String tablename)
  9. dumpTableToFile(Connection con, String table, String fileName)