Example usage for org.apache.commons.dbcp BasicDataSource BasicDataSource

List of usage examples for org.apache.commons.dbcp BasicDataSource BasicDataSource

Introduction

In this page you can find the example usage for org.apache.commons.dbcp BasicDataSource BasicDataSource.

Prototype

BasicDataSource

Source Link

Usage

From source file:BasicDataSourceExample.java

public static void main(String args[]) throws Exception {

    BasicDataSource bds = new BasicDataSource();
    bds.setDriverClassName("com.mysql.jdbc.Driver");
    bds.setUrl("jdbc:mysql://localhost/commons");
    bds.setUsername("root");
    bds.setPassword("");

    //      bds.setInitialSize(5);

    Connection connection = bds.getConnection();

    System.err.println(connection);
    connection.close();//from w  ww  . j  ava  2 s  .  c  o m
}

From source file:com.javacreed.examples.app.Example1.java

public static void main(final String[] args) throws SQLException {
    final BasicDataSource ds = new BasicDataSource();
    ds.setDriverClassName("org.h2.Driver");
    ds.setUrl("jdbc:h2:target/db");
    ds.setUsername("sa");
    ds.setPassword("");

    try (Connection connection = ds.getConnection()) {
        System.out.println("Connected");
    } finally {/* w w w. j a  v a2 s .  c om*/
        ds.close();
    }
}

From source file:mx.com.pixup.portal.demo.DemoDisqueraSelect.java

public static void main(String[] args) {
    System.out.println("BIENVENIDO A PIXUP");
    System.out.println("Mantenimiento catlogo disquera");
    System.out.println("Listado de disqueras");

    Connection connection = null;
    Statement statement = null;/*www .ja v  a2  s  .  co m*/
    ResultSet resultSet = null;
    try {
        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUsername("root");
        dataSource.setPassword("admin");
        dataSource.setUrl("jdbc:mysql://127.0.0.1:3306/pixup");

        connection = dataSource.getConnection();
        statement = connection.createStatement();

        String sql = "select * from disquera order by nombre desc";

        resultSet = statement.executeQuery(sql);

        System.out.println("ID: \t NOMBRE:");
        while (resultSet.next()) {
            Integer id = resultSet.getInt(1);
            String nombre = resultSet.getString(2);
            System.out.println(id + " \t " + nombre);
        }

    } catch (Exception e) {
        System.out.println("Error en el sistema, intente ms tarde!!" + e.getMessage());
    } finally {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (Exception e) {
            }
        }
        if (statement != null) {
            try {
                statement.close();
            } catch (Exception e) {
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (Exception e) {
            }
        }
    }
}

From source file:com.javacreed.examples.app.Example2.java

public static void main(final String[] args) throws SQLException {
    final BasicDataSource ds = new BasicDataSource();
    ds.setDriverClassName("org.h2.Driver");
    ds.setUrl("jdbc:h2:target/db");
    ds.setUsername("sa");
    ds.setPassword("");

    try {//ww  w. j a v a 2  s. c  o  m
        final Flyway flyway = new Flyway();
        flyway.setDataSource(ds);
        flyway.migrate();

        try (Connection connection = ds.getConnection(); Statement stmt = connection.createStatement()) {
            stmt.executeUpdate(
                    "INSERT INTO contacts(name, contacts) VALUES ('Albert Attard', 'albert@javacreed.com')");

            System.out.println("Contacts");
            try (ResultSet rs = stmt.executeQuery("SELECT * FROM contacts")) {
                while (rs.next()) {
                    System.out.printf("  >> [%d] %s (%s)%n", rs.getInt("id"), rs.getString("name"),
                            rs.getString("contacts"));
                }
            }
        }
    } finally {
        ds.close();
    }
}

From source file:com.alibaba.cobar.manager.test.ConnectionTest.java

/**
 * @param args/*from w w  w.  ja  va2s.co  m*/
 */
public static void main(String[] args) {
    try {
        BasicDataSource ds = new BasicDataSource();
        ds.setUsername("test");
        ds.setPassword("");
        ds.setUrl("jdbc:mysql://10.20.153.178:9066/");
        ds.setDriverClassName("com.mysql.jdbc.Driver");
        ds.setMaxActive(-1);
        ds.setMinIdle(0);
        ds.setTimeBetweenEvictionRunsMillis(600000);
        ds.setNumTestsPerEvictionRun(Integer.MAX_VALUE);
        ds.setMinEvictableIdleTimeMillis(GenericObjectPool.DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS);
        Connection conn = ds.getConnection();

        Statement stm = conn.createStatement();
        stm.execute("show @@version");

        ResultSet rst = stm.getResultSet();
        rst.next();
        String version = rst.getString("VERSION");

        System.out.println(version);

    } catch (Exception exception) {
        System.out.println("10.20.153.178:9066   " + exception.getMessage() + exception);
    }
}

From source file:mx.com.pixup.portal.demo.DemoDisqueraDelete.java

public static void main(String[] args) {
    System.out.println("BIENVENIDO A PIXUP");
    System.out.println("Mantenimiento catlogo disquera");
    System.out.println("Inserte el nombre de la disquera a eliminar: ");

    InputStreamReader isr = new InputStreamReader(System.in);
    BufferedReader br = new BufferedReader(isr);
    Connection connection = null;
    Statement statement = null;/*  ww w  .  j a  v a 2  s . c  o  m*/
    try {
        String nombreDisquera = br.readLine();
        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUsername("root");
        dataSource.setPassword("admin");
        dataSource.setUrl("jdbc:mysql://127.0.0.1:3306/pixup");

        connection = dataSource.getConnection();
        statement = connection.createStatement();

        String sql = "delete from disquera where nombre = '" + nombreDisquera + "'";

        statement.execute(sql);

        System.out.println("Disquera: " + nombreDisquera + " eliminada con xito");

    } catch (Exception e) {
        System.out.println("Error en el sistema, intente ms tarde!!");
    } finally {
        if (statement != null) {
            try {
                statement.close();
            } catch (Exception e) {
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (Exception e) {
            }
        }
    }
}

From source file:mx.com.pixup.portal.demo.DemoDisqueraUpdate.java

public static void main(String[] args) {
    System.out.println("BIENVENIDO A PIXUP");
    System.out.println("Mantenimiento catlogo disquera");
    System.out.println("Actualizacin de Disquera");

    InputStreamReader isr = new InputStreamReader(System.in);
    BufferedReader br = new BufferedReader(isr);
    Connection connection = null;
    Statement statement = null;//from   ww  w  .  j  ava  2s  . c o m
    ResultSet resultSet = null;
    try {
        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUsername("root");
        dataSource.setPassword("admin");
        dataSource.setUrl("jdbc:mysql://127.0.0.1:3306/pixup");

        connection = dataSource.getConnection();
        statement = connection.createStatement();

        String sql = "select id, nombre from disquera order by nombre";

        resultSet = statement.executeQuery(sql);

        System.out.println("Id Disquera: \t Nombre Disquera");
        while (resultSet.next()) {
            System.out.println(resultSet.getInt("id") + " \t " + resultSet.getString("nombre"));
        }

        System.out.println("Proporcione el id de la disquera a actualizar: ");
        String idDisquera = br.readLine();

        System.out.println("Proporcione el nuevo nombre de la disquera: ");
        String nombreDisquera = br.readLine();

        sql = "update disquera set nombre = '" + nombreDisquera + "' where id = " + idDisquera;

        statement.execute(sql);

        System.out.println("Disqueras Actualizadas:");

        sql = "select id, nombre from disquera order by nombre desc";

        resultSet = statement.executeQuery(sql);

        System.out.println("Id Disquera: \t Nombre Disquera");
        while (resultSet.next()) {
            System.out.println(resultSet.getInt("id") + " \t " + resultSet.getString("nombre"));
        }

    } catch (Exception e) {
        System.out.println("Error en el sistema, intente ms tarde!!");
    } finally {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (Exception e) {
            }
        }
        if (statement != null) {
            try {
                statement.close();
            } catch (Exception e) {
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (Exception e) {
            }
        }
    }
}

From source file:com.javacreed.examples.app.Main.java

public static void main(final String[] args) {

    Main.LOGGER.debug("Creating the data source");
    final BasicDataSource ds = new BasicDataSource();
    ds.setDriverClassName("org.h2.Driver");
    ds.setUrl("jdbc:h2:target/db");
    ds.setUsername("sa");
    ds.setPassword("");

    try {//from  w  w  w .  j  a va  2  s. c o m
        Main.LOGGER.debug("Executing Flyway (database migration)");
        final Flyway flyway = new Flyway();
        flyway.setDataSource(ds);
        flyway.migrate();

        try (Connection connection = ds.getConnection(); Statement stmt = connection.createStatement()) {
            stmt.executeUpdate(
                    "INSERT INTO contacts(name, contacts) VALUES ('Albert Attard', 'albert@javacreed.com')");

            Main.LOGGER.debug("Contacts");
            try (ResultSet rs = stmt.executeQuery("SELECT * FROM contacts")) {
                while (rs.next()) {
                    Main.LOGGER.debug("  >> [{}] {} ({})", rs.getInt("id"), rs.getString("name"),
                            rs.getString("contacts"));
                }
            }
        } catch (final SQLException e) {
            Main.LOGGER.error("Failed", e);
        }
    } finally {
        try {
            ds.close();
        } catch (final SQLException e) {
            Main.LOGGER.error("Failed to close the data source", e);
        }
    }
}

From source file:com.gnizr.db.dao.util.MySQLDBExport.java

public static void main(String[] args) throws Exception {
    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setUsername("gnizr");
    dataSource.setPassword("gnizr");
    dataSource.setUrl("jdbc:mysql://localhost/gnizr_db");
    dataSource.setDriverClassName("com.mysql.jdbc.Driver");

    IDatabaseConnection dc = new DatabaseConnection(dataSource.getConnection());
    DatabaseConfig config = dc.getConfig();
    config.setProperty(DatabaseConfig.PROPERTY_DATATYPE_FACTORY, new MySqlDataTypeFactory());

    // full database export
    IDataSet fullDataSet = dc.createDataSet();
    FlatXmlDataSet.write(fullDataSet, new FileOutputStream("full.xml"));
}

From source file:ch.aranea.test.SparkCRUD.java

public static void main(String[] args) throws Exception {
    final BasicDataSource ds = new BasicDataSource();

    ds.setDriverClassName("org.h2.Driver");
    ds.setUrl("jdbc:h2:tcp://localhost/~/test");
    ds.setUsername("sa");
    ds.setPassword("");

    final DSLContext ctx = DSL.using(ds, SQLDialect.H2);

    // Creates a new book resource, will return the ID to the created resource
    // author and title are sent as query parameters e.g. /books?author=Foo&title=Bar
    post("/books", (request, response) -> {
        AuthorRecord author = upsertAuthor(ctx, request);

        BookRecord book = ctx.newRecord(BOOK);
        book.setAuthorId(author.getId());
        book.setTitle(request.queryParams("title"));
        book.store();//  www  .  j  a v  a2  s.  c  o m

        response.status(201); // 201 Created
        return book.getId();
    });

    // Gets the book resource for the provided id
    get("/books/:id", (request, response) -> {
        Record2<String, String> book = ctx.select(BOOK.TITLE, AUTHOR.NAME).from(BOOK).join(AUTHOR)
                .on(BOOK.AUTHOR_ID.eq(AUTHOR.ID))
                .where(BOOK.ID.eq(BOOK.ID.getDataType().convert(request.params(":id")))).fetchOne();

        if (book != null) {
            return "Title: " + book.value1() + ", Author: " + book.value2();
        } else {
            response.status(404); // 404 Not found
            return "Book not found";
        }
    });

    // Updates the book resource for the provided id with new information
    // author and title are sent as query parameters e.g. /books/<id>?author=Foo&title=Bar
    put("/books/:id", (request, response) -> {
        BookRecord book = ctx.selectFrom(BOOK)
                .where(BOOK.ID.eq(BOOK.ID.getDataType().convert(request.params(":id")))).fetchOne();

        if (book != null) {
            AuthorRecord author = upsertAuthor(ctx, request);

            String newAuthor = request.queryParams("author");
            String newTitle = request.queryParams("title");

            if (newAuthor != null) {
                book.setAuthorId(author.getId());
            }
            if (newTitle != null) {
                book.setTitle(newTitle);
            }

            book.update();
            return "Book with id '" + book.getId() + "' updated";
        } else {
            response.status(404); // 404 Not found
            return "Book not found";
        }
    });

    // Deletes the book resource for the provided id
    delete("/books/:id", (request, response) -> {
        BookRecord book = ctx.deleteFrom(BOOK)
                .where(BOOK.ID.eq(BOOK.ID.getDataType().convert(request.params(":id")))).returning().fetchOne();

        if (book != null) {
            return "Book with id '" + book.getId() + "' deleted";
        } else {
            response.status(404); // 404 Not found
            return "Book not found";
        }
    });

    // Gets all available book resources
    get("/books", (request, response) -> {
        return ctx.selectFrom(BOOK).fetch().formatJSON();
    });
}