Java JDBC MySQL Connection createTable(String dbFile, String tableName, String tableDefinition)

Here you can find the source of createTable(String dbFile, String tableName, String tableDefinition)

Description

create Table

License

Open Source License

Declaration

public static void createTable(String dbFile, String tableName, String tableDefinition) throws SQLException 

Method Source Code


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

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;

public class Main {
    private final static Map<String, Connection> connections = new HashMap<>();

    public static void createTable(String dbFile, String tableName, String tableDefinition) throws SQLException {
        checkConnection(dbFile);//from   ww w .j  a  v  a 2  s  .  com

        Connection connection = getConnection(dbFile);

        Statement statement = connection.createStatement();
        String sql = "create table " + tableName + " (" + tableDefinition + ")";

        System.out.println(sql);
        statement.executeUpdate(sql);

        statement.close();
    }

    private static void checkConnection(String dbFile) {
        try {
            Connection connection = connections.get(dbFile);

            if (connection.isClosed())
                initializeConnection(dbFile);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public static Connection getConnection(String dbFile) {
        checkConnection(dbFile);
        return connections.get(dbFile);
    }

    public synchronized static void initializeConnection(String dbFile) {
        try {
            Connection connection = DriverManager.getConnection(getDbURL(dbFile));

            connections.put(dbFile, connection);
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }

    }

    public static String getDbURL(String dbFile) {
        return "jdbc:h2:" + dbFile + ";MODE=MySQL;FILE_LOCK=NO";
    }
}

Related

  1. computeAverageGeneIdsPerName()
  2. createConnection()
  3. createConnection(String hostname, String port, String database, String username, String password)
  4. createConnection(String url, String user, String password)
  5. createConnectionUtf8(String connString)
  6. deleteTableData(String tableName)
  7. getAllNames()
  8. getConnection()
  9. getConnection()