Create Database Table - Java java.sql

Java examples for java.sql:Table

Description

Create Database Table

Demo Code


//package com.java2s;
import java.sql.*;

public class Main {

    public static Connection createTable(String driver, String url,
            String username, String password, String tableName,
            String tableFormat, String[] tableRows, boolean close) {
        try {// w w w .  ja  v  a  2s  .c om
            Class.forName(driver);
            Connection connection = DriverManager.getConnection(url,
                    username, password);
            return (createTable(connection, username, password, tableName,
                    tableFormat, tableRows, close));
        } catch (ClassNotFoundException cnfe) {
            System.err.println("B??d ?adowania sterownika: " + cnfe);
            return (null);
        } catch (SQLException sqle) {
            System.err
                    .println("B??d przy nawi?zywaniu po??czenia: " + sqle);
            return (null);
        }
    }

    public static Connection createTable(Connection connection,
            String username, String password, String tableName,
            String tableFormat, String[] tableRows, boolean close) {
        try {

            Statement statement = connection.createStatement();
            // Usuwa aktualn? tabel? je?li taka istnieje, lecz nie zg?asza b??d?w
            // je?li tablie nie ma. Do tego celu s?u?y osobny blok try/catch.
            try {
                statement.execute("DROP TABLE " + tableName);
            } catch (SQLException sqle) {
            }
            String createCommand = "CREATE TABLE " + tableName + " "
                    + tableFormat;
            statement.execute(createCommand);
            String insertPrefix = "INSERT INTO " + tableName + " VALUES";
            for (int i = 0; i < tableRows.length; i++) {
                statement.execute(insertPrefix + tableRows[i]);
            }
            if (close) {
                connection.close();
                return (null);
            } else {
                return (connection);
            }
        } catch (SQLException sqle) {
            System.err.println("B??d przy tworzeniu tabeli: " + sqle);
            return (null);
        }
    }
}

Related Tutorials