create Derby Embedded Data Source - Java java.sql

Java examples for java.sql:Derby

Description

create Derby Embedded Data Source

Demo Code

/*/*w w w  .  j a  va2 s  .  com*/
# Licensed Materials - Property of IBM
# Copyright IBM Corp. 2015, 2016 
 */
//package com.java2s;
import java.lang.reflect.Method;

import java.util.Properties;
import javax.sql.DataSource;

public class Main {
    private static DataSource createDerbyEmbeddedDataSource(Properties props)
            throws Exception {
        String dbName = props.getProperty("db.name",
                "JdbcConnectorSampleDb");

        // For our sample, avoid a compile-time dependency to the jdbc driver.
        // At runtime, require that the classpath can find it.

        String DERBY_DATA_SOURCE = "org.apache.derby.jdbc.EmbeddedDataSource";

        Class<?> nsDataSource = null;
        try {
            nsDataSource = Class.forName(DERBY_DATA_SOURCE);
        } catch (ClassNotFoundException e) {
            String msg = "Fix the test classpath. ";
            if (System.getenv("DERBY_HOME") == null) {
                msg += "DERBY_HOME not set. ";
            }
            msg += "Class not found: " + e.getLocalizedMessage();
            System.err.println(msg);
            throw new IllegalStateException(msg);
        }
        DataSource ds = (DataSource) nsDataSource.newInstance();

        @SuppressWarnings("rawtypes")
        Class[] methodParams = new Class[] { String.class };
        Method dbname = nsDataSource.getMethod("setDatabaseName",
                methodParams);
        Object[] args = new Object[] { dbName };
        dbname.invoke(ds, args);

        // create the db if necessary
        Method create = nsDataSource.getMethod("setCreateDatabase",
                methodParams);
        args = new Object[] { "create" };
        create.invoke(ds, args);

        // set the user
        Method setuser = nsDataSource.getMethod("setUser", methodParams);
        args = new Object[] { props.getProperty("db.user",
                System.getProperty("user.name")) };
        setuser.invoke(ds, args);

        // optionally set the pw
        Method setpw = nsDataSource.getMethod("setPassword", methodParams);
        args = new Object[] { props.getProperty("db.password") };
        if (args[0] != null)
            setpw.invoke(ds, args);

        return ds;
    }
}

Related Tutorials