Example usage for javax.sql DataSource getConnection

List of usage examples for javax.sql DataSource getConnection

Introduction

In this page you can find the example usage for javax.sql DataSource getConnection.

Prototype

Connection getConnection() throws SQLException;

Source Link

Document

Attempts to establish a connection with the data source that this DataSource object represents.

Usage

From source file:ManualPoolingDataSourceExample.java

public static void main(String[] args) {
    ////w  ww  .  ja v a 2  s . com
    // First we load the underlying JDBC driver.
    // You need this if you don't use the jdbc.drivers
    // system property.
    //
    System.out.println("Loading underlying JDBC driver.");
    try {
        Class.forName("oracle.jdbc.driver.OracleDriver");
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
    System.out.println("Done.");

    //
    // Then, we set up the PoolingDataSource.
    // Normally this would be handled auto-magically by
    // an external configuration, but in this example we'll
    // do it manually.
    //
    System.out.println("Setting up data source.");
    DataSource dataSource = setupDataSource(args[0]);
    System.out.println("Done.");

    //
    // Now, we can use JDBC DataSource as we normally would.
    //
    Connection conn = null;
    Statement stmt = null;
    ResultSet rset = null;

    try {
        System.out.println("Creating connection.");
        conn = dataSource.getConnection();
        System.out.println("Creating statement.");
        stmt = conn.createStatement();
        System.out.println("Executing statement.");
        rset = stmt.executeQuery(args[1]);
        System.out.println("Results:");
        int numcols = rset.getMetaData().getColumnCount();
        while (rset.next()) {
            for (int i = 1; i <= numcols; i++) {
                System.out.print("\t" + rset.getString(i));
            }
            System.out.println("");
        }
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        try {
            if (rset != null)
                rset.close();
        } catch (Exception e) {
        }
        try {
            if (stmt != null)
                stmt.close();
        } catch (Exception e) {
        }
        try {
            if (conn != null)
                conn.close();
        } catch (Exception e) {
        }
    }
}

From source file:Commons.dbcp.ManualPoolingDataSourceExample.java

public static void main(String[] args) {
    ///*from  ww  w.  ja  v a  2 s .c om*/
    // First we load the underlying JDBC driver.
    // You need this if you don't use the jdbc.drivers
    // system property.
    //
    System.out.println("Loading underlying JDBC driver.");
    try {
        Class.forName("oracle.jdbc.driver.OracleDriver");
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
    System.out.println("Done.");

    //
    // Then, we set up the PoolingDataSource.
    // Normally this would be handled auto-magically by
    // an external configuration, but in this example we'll
    // do it manually.
    //
    System.out.println("Setting up data source.");
    ////ee  DataSource dataSource = setupDataSource(args[0]);
    DataSource dataSource = setupDataSource("jdbc:oracle:thin:@10.1.1.184:1521:UTF8");
    System.out.println("Done.");

    //
    // Now, we can use JDBC DataSource as we normally would.
    //
    Connection conn = null;
    Statement stmt = null;
    ResultSet rset = null;

    try {
        System.out.println("Creating connection.");
        conn = dataSource.getConnection();
        System.out.println("Creating statement.");
        stmt = conn.createStatement();
        System.out.println("Executing statement.");
        rset = stmt.executeQuery(args[1]);
        System.out.println("Results:");
        int numcols = rset.getMetaData().getColumnCount();
        while (rset.next()) {
            for (int i = 1; i <= numcols; i++) {
                System.out.print("\t" + rset.getString(i));
            }
            System.out.println("");
        }
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        try {
            rset.close();
        } catch (Exception e) {
        }
        try {
            stmt.close();
        } catch (Exception e) {
        }
        try {
            conn.close();
        } catch (Exception e) {
        }
    }
}

From source file:com.jt.dbcp.example.ManualPoolingDataSourceExample.java

public static void main(String[] args) throws SQLException {
    ///*from  ww w  . j  av a2 s . c  o  m*/
    // First we load the underlying JDBC driver.
    // You need this if you don't use the jdbc.drivers
    // system property.
    //
    System.out.println("Loading underlying JDBC driver.");
    try {
        Class.forName("com.mysql.jdbc.Driver");
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
    System.out.println("Done.");

    //
    // Then, we set up the PoolingDataSource.
    // Normally this would be handled auto-magically by
    // an external configuration, but in this example we'll
    // do it manually.
    //
    System.out.println("Setting up data source.");
    DataSource dataSource = setupDataSource(args[0]);
    System.out.println("Done.");

    //
    // Now, we can use JDBC DataSource as we normally would.
    //
    Connection conn = null;
    Statement stmt = null;
    ResultSet rset = null;

    try {
        System.out.println("Creating connection.");
        conn = dataSource.getConnection();
        System.out.println("Creating statement.");
        stmt = conn.createStatement();
        System.out.println("Executing statement.");
        rset = stmt.executeQuery(args[1]);
        System.out.println("Results:");
        int numcols = rset.getMetaData().getColumnCount();
        int count = 0;
        while (rset.next()) {
            count++;
            if (count == 10) {
                break;
            }
            for (int i = 1; i <= numcols; i++) {
                System.out.print("\t" + rset.getString(i));
            }
            System.out.println("");
        }
        printDataSourceStats(dataSource);
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        try {
            if (rset != null)
                rset.close();
        } catch (Exception e) {
        }
        try {
            if (stmt != null)
                stmt.close();
        } catch (Exception e) {
        }
        try {
            if (conn != null)
                conn.close();
        } catch (Exception e) {
        }
        //            shutdownDataSource(dataSource);
    }
}

From source file:javax.arang.DB.dbcp.ManualPoolingDataSourceExample.java

public static void main(String[] args) {
    ///*from   ww w.j  a  va2 s  . c o m*/
    // First we load the underlying JDBC driver.
    // You need this if you don't use the jdbc.drivers
    // system property.
    //
    System.out.println("Loading underlying JDBC driver.");
    try {
        Class.forName("com.mysql.jdbc.Driver");
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
    System.out.println("Done.");

    //
    // Then, we set up the PoolingDataSource.
    // Normally this would be handled auto-magically by
    // an external configuration, but in this example we'll
    // do it manually.
    //
    System.out.println("Setting up data source.");
    DataSource dataSource = setupDataSource("jdbc:mysql://root@localhost:3306:root:dkfkdsid");
    System.out.println("Done.");

    //
    // Now, we can use JDBC DataSource as we normally would.
    //
    Connection conn = null;
    Statement stmt = null;
    ResultSet rset = null;

    try {
        System.out.println("Creating connection.");
        conn = dataSource.getConnection();
        System.out.println("Creating statement.");
        stmt = conn.createStatement();
        System.out.println("Executing statement.");
        rset = stmt.executeQuery(args[1]);
        System.out.println("Results:");
        int numcols = rset.getMetaData().getColumnCount();
        while (rset.next()) {
            for (int i = 1; i <= numcols; i++) {
                System.out.print("\t" + rset.getString(i));
            }
            System.out.println("");
        }
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        try {
            if (rset != null)
                rset.close();
        } catch (Exception e) {
        }
        try {
            if (stmt != null)
                stmt.close();
        } catch (Exception e) {
        }
        try {
            if (conn != null)
                conn.close();
        } catch (Exception e) {
        }
    }
}

From source file:org.dspace.storage.rdbms.DatabaseUtils.java

/**
 * Commandline tools for managing database changes, etc.
 * @param argv the command line arguments given
 *//* www .  j  a v  a 2s. c o  m*/
public static void main(String[] argv) {
    // Usage checks
    if (argv.length < 1) {
        System.out.println("\nDatabase action argument is missing.");
        System.out.println("Valid actions: 'test', 'info', 'migrate', 'repair', 'validate' or 'clean'");
        System.out.println("\nOr, type 'database help' for more information.\n");
        System.exit(1);
    }

    try {
        // Get a reference to our configured DataSource
        DataSource dataSource = getDataSource();

        // Point Flyway API to our database
        Flyway flyway = setupFlyway(dataSource);

        // "test" = Test Database Connection
        if (argv[0].equalsIgnoreCase("test")) {
            // Try to connect to the database
            System.out.println("\nAttempting to connect to database");
            try (Connection connection = dataSource.getConnection()) {
                System.out.println("Connected successfully!");

                // Print basic database connection information
                printDBInfo(connection);

                // Print any database warnings/errors found (if any)
                boolean issueFound = printDBIssues(connection);

                // If issues found, exit with an error status (even if connection succeeded).
                if (issueFound)
                    System.exit(1);
                else
                    System.exit(0);
            } catch (SQLException sqle) {
                System.err.println("\nError running 'test': ");
                System.err.println(" - " + sqle);
                System.err.println("\nPlease see the DSpace documentation for assistance.\n");
                sqle.printStackTrace();
                System.exit(1);
            }
        } else if (argv[0].equalsIgnoreCase("info") || argv[0].equalsIgnoreCase("status")) {
            try (Connection connection = dataSource.getConnection()) {
                // Print basic Database info
                printDBInfo(connection);

                // Get info table from Flyway
                System.out.println("\n" + MigrationInfoDumper.dumpToAsciiTable(flyway.info().all()));

                // If Flyway is NOT yet initialized, also print the determined version information
                // NOTE: search is case sensitive, as flyway table name is ALWAYS lowercase,
                // See: http://flywaydb.org/documentation/faq.html#case-sensitive
                if (!tableExists(connection, flyway.getTable(), true)) {
                    System.out.println(
                            "\nNOTE: This database is NOT yet initialized for auto-migrations (via Flyway).");
                    // Determine which version of DSpace this looks like
                    String dbVersion = determineDBVersion(connection);
                    if (dbVersion != null) {
                        System.out.println(
                                "\nYour database looks to be compatible with DSpace version " + dbVersion);
                        System.out.println("All upgrades *after* version " + dbVersion
                                + " will be run during the next migration.");
                        System.out.println(
                                "\nIf you'd like to upgrade now, simply run 'dspace database migrate'.");
                    }
                }

                // Print any database warnings/errors found (if any)
                boolean issueFound = printDBIssues(connection);

                // If issues found, exit with an error status
                if (issueFound)
                    System.exit(1);
                else
                    System.exit(0);
            } catch (SQLException e) {
                System.err.println("Info exception:");
                e.printStackTrace();
                System.exit(1);
            }
        } else if (argv[0].equalsIgnoreCase("migrate")) {
            try (Connection connection = dataSource.getConnection()) {
                System.out.println("\nDatabase URL: " + connection.getMetaData().getURL());

                // "migrate" allows for an OPTIONAL second argument:
                //    - "ignored" = Also run any previously "ignored" migrations during the migration
                //    - [version] = ONLY run migrations up to a specific DSpace version (ONLY FOR TESTING)
                if (argv.length == 2) {
                    if (argv[1].equalsIgnoreCase("ignored")) {
                        System.out.println(
                                "Migrating database to latest version AND running previously \"Ignored\" migrations... (Check logs for details)");
                        // Update the database to latest version, but set "outOfOrder=true"
                        // This will ensure any old migrations in the "ignored" state are now run
                        updateDatabase(dataSource, connection, null, true);
                    } else {
                        // Otherwise, we assume "argv[1]" is a valid migration version number
                        // This is only for testing! Never specify for Production!
                        String migrationVersion = argv[1];
                        BufferedReader input = new BufferedReader(new InputStreamReader(System.in));

                        System.out.println("You've specified to migrate your database ONLY to version "
                                + migrationVersion + " ...");
                        System.out.println(
                                "\nWARNING: It is highly likely you will see errors in your logs when the Metadata");
                        System.out.println(
                                "or Bitstream Format Registry auto-update. This is because you are attempting to");
                        System.out.println("use an OLD version " + migrationVersion
                                + " Database with a newer DSpace API. NEVER do this in a");
                        System.out.println(
                                "PRODUCTION scenario. The resulting old DB is only useful for migration testing.\n");

                        System.out.print("Are you SURE you only want to migrate your database to version "
                                + migrationVersion + "? [y/n]: ");
                        String choiceString = input.readLine();
                        input.close();

                        if (choiceString.equalsIgnoreCase("y")) {
                            System.out.println("Migrating database ONLY to version " + migrationVersion
                                    + " ... (Check logs for details)");
                            // Update the database, to the version specified.
                            updateDatabase(dataSource, connection, migrationVersion, false);
                        } else {
                            System.out.println("No action performed.");
                        }
                    }
                } else {
                    System.out
                            .println("Migrating database to latest version... (Check dspace logs for details)");
                    updateDatabase(dataSource, connection);
                }
                System.out.println("Done.");
                System.exit(0);
            } catch (SQLException e) {
                System.err.println("Migration exception:");
                e.printStackTrace();
                System.exit(1);
            }
        }
        // "repair" = Run Flyway repair script
        else if (argv[0].equalsIgnoreCase("repair")) {
            try (Connection connection = dataSource.getConnection();) {
                System.out.println("\nDatabase URL: " + connection.getMetaData().getURL());
                System.out.println(
                        "Attempting to repair any previously failed migrations (or mismatched checksums) via FlywayDB... (Check dspace logs for details)");
                flyway.repair();
                System.out.println("Done.");
                System.exit(0);
            } catch (SQLException | FlywayException e) {
                System.err.println("Repair exception:");
                e.printStackTrace();
                System.exit(1);
            }
        }
        // "validate" = Run Flyway validation to check for database errors/issues
        else if (argv[0].equalsIgnoreCase("validate")) {
            try (Connection connection = dataSource.getConnection();) {
                System.out.println("\nDatabase URL: " + connection.getMetaData().getURL());
                System.out.println(
                        "Attempting to validate database status (and migration checksums) via FlywayDB...");
                flyway.validate();
                System.out.println(
                        "No errors thrown. Validation succeeded. (Check dspace logs for more details)");
                System.exit(0);
            } catch (SQLException | FlywayException e) {
                System.err.println("Validation exception:");
                e.printStackTrace();
                System.exit(1);
            }
        }
        // "clean" = Run Flyway clean script
        else if (argv[0].equalsIgnoreCase("clean")) {
            // If clean is disabled, return immediately
            if (flyway.isCleanDisabled()) {
                System.out.println(
                        "\nWARNING: 'clean' command is currently disabled, as it is dangerous to run in Production scenarios!");
                System.out.println(
                        "\nIn order to run a 'clean' you first must enable it in your DSpace config by specifying 'db.cleanDisabled=false'.\n");
                System.exit(1);
            }

            try (Connection connection = dataSource.getConnection()) {
                String dbType = getDbType(connection);

                // Not all Postgres user accounts will be able to run a 'clean',
                // as only 'superuser' accounts can remove the 'pgcrypto' extension.
                if (dbType.equals(DBMS_POSTGRES)) {
                    // Check if database user has permissions suitable to run a clean
                    if (!PostgresUtils.checkCleanPermissions(connection)) {
                        String username = connection.getMetaData().getUserName();
                        // Exit immediately, providing a descriptive error message
                        System.out.println("\nERROR: The database user '" + username
                                + "' does not have sufficient privileges to run a 'database clean' (via Flyway).");
                        System.out.println(
                                "\nIn order to run a 'clean', the database user MUST have 'superuser' privileges");
                        System.out.println("OR the '" + PostgresUtils.PGCRYPTO
                                + "' extension must be installed in a separate schema (see documentation).");
                        System.out.println("\nOptionally, you could also manually remove the '"
                                + PostgresUtils.PGCRYPTO + "' extension first (DROP EXTENSION "
                                + PostgresUtils.PGCRYPTO + " CASCADE;), then rerun the 'clean'");
                        System.exit(1);
                    }
                }

                BufferedReader input = new BufferedReader(new InputStreamReader(System.in));

                System.out.println("\nDatabase URL: " + connection.getMetaData().getURL());
                System.out.println(
                        "\nWARNING: ALL DATA AND TABLES IN YOUR DATABASE WILL BE PERMANENTLY DELETED.\n");
                System.out.println(
                        "There is NO turning back from this action. Backup your DB before continuing.");
                if (dbType.equals(DBMS_ORACLE)) {
                    System.out.println("\nORACLE WARNING: your RECYCLEBIN will also be PURGED.\n");
                } else if (dbType.equals(DBMS_POSTGRES)) {
                    System.out.println("\nPOSTGRES WARNING: the '" + PostgresUtils.PGCRYPTO
                            + "' extension will be dropped if it is in the same schema as the DSpace database.\n");
                }
                System.out.print("Do you want to PERMANENTLY DELETE everything from your database? [y/n]: ");
                String choiceString = input.readLine();
                input.close();

                if (choiceString.equalsIgnoreCase("y")) {
                    System.out.println("Scrubbing database clean... (Check dspace logs for details)");
                    cleanDatabase(flyway, dataSource);
                    System.out.println("Done.");
                    System.exit(0);
                } else {
                    System.out.println("No action performed.");
                }
            } catch (SQLException e) {
                System.err.println("Clean exception:");
                e.printStackTrace();
                System.exit(1);
            }
        } else {
            System.out.println("\nUsage: database [action]");
            System.out.println("Valid actions: 'test', 'info', 'migrate', 'repair' or 'clean'");
            System.out.println(
                    " - test          = Performs a test connection to database to validate connection settings");
            System.out.println(
                    " - info / status = Describe basic info/status about database, including validating the compatibility of this database");
            System.out.println(" - migrate       = Migrate the database to the latest version");
            System.out.println(
                    " - repair        = Attempt to repair any previously failed database migrations or checksum mismatches (via Flyway repair)");
            System.out.println(
                    " - validate      = Validate current database's migration status (via Flyway validate), validating all migration checksums.");
            System.out.println(
                    " - clean         = DESTROY all data and tables in database (WARNING there is no going back!). Requires 'db.cleanDisabled=false' setting in config.");
            System.out.println("");
            System.exit(0);
        }

    } catch (Exception e) {
        System.err.println("Caught exception:");
        e.printStackTrace();
        System.exit(1);
    }
}

From source file:org.neuro4j.sitedemo.util.DBUtils.java

public static Connection getConnection() throws SQLException {
    DataSource ds = (DataSource) context.getBean("dataSource");

    return ds.getConnection();
}

From source file:com.xpfriend.fixture.runner.example.ExampleJob.java

/**
 * ???//from w w  w  .j  a v a 2  s.c o m
 * @return ?
 */
private static Connection getConnection() throws Exception, IOException, SQLException {
    DataSource ds = BasicDataSourceFactory.createDataSource(getProperties());
    return ds.getConnection();
}

From source file:uk.co.blackpepper.support.spring.jdbc.test.EmbeddedDatabaseRuleTest.java

private static void executeSql(DataSource dataSource, String sql) throws SQLException {
    dataSource.getConnection().prepareStatement(sql).execute();
}

From source file:jongo.jdbc.JDBCConnectionFactory.java

/**
 * Gives access to a {@link java.sql.Connection} for the given database.
 * @param dbcfg a registered {@link jongo.config.DatabaseConfiguration}
 * @return a {@link java.sql.Connection}
 * @throws SQLException //  w  w  w  .  j ava2 s  .co m
 */
public static Connection getConnection(final DatabaseConfiguration dbcfg) throws SQLException {
    l.debug("Obtaining a connection from the datasource");
    DataSource ds = getDataSource(dbcfg);
    return ds.getConnection();
}

From source file:com.artivisi.security.service.impl.SpringSecurityServiceImplTest.java

@SuppressWarnings("unused")
private static void clearDatabase() throws SQLException {
    DataSource ds = (DataSource) applicationContext.getBean("dataSource");
    Connection conn = ds.getConnection();
    conn.createStatement().executeUpdate("truncate users");
    conn.createStatement().executeUpdate("truncate groups_authority");
    conn.createStatement().executeUpdate("truncate groups");
    conn.createStatement().executeUpdate("truncate role");
    conn.close();//from  ww w  .  ja  v  a2 s.  co m
}