// Collection of code snippets by Arne Vajhøj 
// (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) 
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Random;

public class MySQLTest {
    private final static int NREC = 2000000;
    private final static int SAMPSIZ = 250000;
    private final static int MVAL = 25000;
    private static Random rng = new Random(1234567);
    private static NumberFormat nf = new DecimalFormat("0.0");
    public static void main(String[] args) throws Exception {
        Class.forName("com.mysql.jdbc.Driver");
        Connection con = DriverManager.getConnection("jdbc:mysql://localhost/Test", "", "");
        Statement stmt = con.createStatement();
        //stmt.executeUpdate("CREATE TABLE big (f1 BIGINT NOT NULL, f2 BIGINT NOT NULL, PRIMARY KEY(f1,f2))");
        stmt.executeUpdate("CREATE TABLE big (f1 BIGINT NOT NULL, f2 BIGINT NOT NULL, PRIMARY KEY(f1,f2)) DELAY_KEY_WRITE=1");
        //stmt.executeUpdate("CREATE TABLE big (f1 BIGINT NOT NULL, f2 BIGINT NOT NULL)");
        StringBuffer sqlstr = new StringBuffer("INSERT INTO big VALUES ");
        for(int j = 0; j < MVAL; j++) {
            if(j > 0) sqlstr.append(",");
            sqlstr.append("(?,?)");
        }
        PreparedStatement pstmt = con.prepareStatement(sqlstr.toString());
        long t1 = System.currentTimeMillis();
        long t2;
        for (int i = 0; i < NREC; i = i + MVAL) {
            for(int j = 0; j < MVAL; j++) {
                pstmt.setLong(2 * j + 1, rng.nextLong());
                pstmt.setLong(2 * j + 2, rng.nextLong());
            }
            pstmt.executeUpdate();
            if(((i + MVAL) % SAMPSIZ) == 0) {
                t2 = System.currentTimeMillis();
                System.out.println(nf.format((t2 - t1)/1000.0) + " seconds to add " + SAMPSIZ + " records" );
                t1 = t2;
            }
        }
        pstmt.close();
        //stmt.executeUpdate("ALTER TABLE big ADD PRIMARY KEY(f1,f2)");
        //t2 = System.currentTimeMillis();
        //System.out.println(nf.format((t2 - t1)/1000.0) + " seconds to add PK");
        ResultSet rs = stmt.executeQuery("SELECT COUNT(*) FROM big");
        rs.next();
        System.out.println(rs.getInt(1) + " records inserted");
        stmt.executeUpdate("DROP TABLE big");
        stmt.close();
        con.close();
    }
}
