com.dbconnection.DataSourceConnection.java Source code

Java tutorial

Introduction

Here is the source code for com.dbconnection.DataSourceConnection.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.dbconnection;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.sql.DataSource;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

// importar la clase de javaRow
import javax.sql.rowset.JdbcRowSet;
import com.sun.rowset.JdbcRowSetImpl;

public class DataSourceConnection {

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

        ApplicationContext appContext = new ClassPathXmlApplicationContext("beans.xml");
        DataSource dataSource = (DataSource) appContext.getBean("dataSource");

        Connection connection = dataSource.getConnection();
        System.out.println("Database with data source connected!");
        String result = query(connection);
        System.out.println(result);

    }

    public JdbcRowSet getJdbcRowSet() throws SQLException {

        ApplicationContext appContext = new ClassPathXmlApplicationContext("beans.xml");
        DataSource datSour = (DataSource) appContext.getBean("dataSource");

        JdbcRowSet jr = new JdbcRowSetImpl(datSour.getConnection());
        return jr;
    }

    private static String query(Connection connection) throws SQLException {

        String query = "";
        Statement statement = connection.createStatement();

        ResultSet resultSet = statement.executeQuery("SELECT * FROM BOOK");

        while (resultSet.next()) {
            int id = resultSet.getInt("id");
            String title = resultSet.getString("title");

            query = query + id + "\t" + title + "\n";
        }
        return query;
    }

}