create Table If Missing in h2 database - Java java.sql

Java examples for java.sql:h2

Description

create Table If Missing in h2 database

Demo Code


//package com.java2s;
import java.sql.Connection;
import java.sql.DriverManager;

import java.sql.SQLException;
import java.sql.Statement;

public class Main {
    private static final String DB_CONN_URL = "jdbc:h2:file:~/h2db";
    private static final String USERNAME = "surya";
    private static final String PASSWORD = "kiran";

    public static void createTableIfMissing() {
        String createStatement = "create table users (name varchar(50))";
        try (Connection conn = getConnection();
                Statement stmt = conn.createStatement();) {
            stmt.executeUpdate(createStatement);
        } catch (ClassNotFoundException | SQLException e) {

        }//w  w  w . j ava 2  s .c  o m
    }

    public static Connection getConnection() throws SQLException,
            ClassNotFoundException {
        Class.forName("org.h2.Driver");
        Connection conn = DriverManager.getConnection(DB_CONN_URL,
                USERNAME, PASSWORD);

        return conn;
    }
}

Related Tutorials