java examples
Home Java Examples Resources Java Interview Questions
Brainpower SEO

How to create a Data Source object for JdbcTemplate?

In this example you will learn how to create and configure a DriverManagerDataSource object that will be used by the JdbcTemplate object. There are some information required when creating a DataSource including the JDBC driver class, the JDBC Url of the target database, the username and password for connecting to database server.

package com.javacoderanch.example.spring.jdbc;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

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

public class SpringJdbcDataSource {
    public static final String DRIVER   = "com.mysql.jdbc.Driver";
    public static final String JDBC_URL = "jdbc:mysql://localhost/javacoderanchdb";
    public static final String USERNAME = "root";
    public static final String PASSWORD = "";

    public static void main(String[] args) {
        //
        // Creates an instance of DriverManagerDataSource and pass
        // it to the JdbcTemplate.
        //
        DataSource source = getDataSource();
        JdbcTemplate template = new JdbcTemplate(source);

        //
        // After creating a template with a data source inject we
        // can do a database manipulation such as the CRUD operation.
        //
        System.out.println("DataSource = " + template.getDataSource());
        List products = template.queryForList("SELECT * FROM products");
        for (int i = 0; i < products.size(); i++) {
            System.out.println("Products = " + products.get(i));
        }
    }

    /**
     * Returns a DataSource object for connection to the database.
     * @return a DataSource.
     */
    private static DataSource getDataSource() {
        //
        // Creates a new instance of DriverManagerDataSource and sets
        // the required parameters such as the Jdbc Driver class,
        // Jdbc URL, database user name and password. 
        //
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(SpringJdbcDataSource.DRIVER);
        dataSource.setUrl(SpringJdbcDataSource.JDBC_URL);
        dataSource.setUsername(SpringJdbcDataSource.USERNAME);
        dataSource.setPassword(SpringJdbcDataSource.PASSWORD);
        return dataSource;
    }
}