2017  Kodetalk | Feedback | Privacy Policy | Terms | About
userimage

How can i create a Data Source object for JdbcTemplate using Spring jdbc module?

How can i create a Data Source object for JdbcTemplate using Spring jdbc module?

userimage

Try below code:

import java.util.List;

import javax.sql.DataSource;

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

public class SpringJDBCDataSource {

   public static final String DRIVER = "com.mysql.jdbc.Driver";
   public static final String JDBC_URL = "jdbc:mysql://localhost/yourdatabase";
   public static final String USERNAME = "root";
   public static final String PASSWORD = "password";

   public static void main(String[] args) {
       DataSource source = getDataSource();
       JdbcTemplate template = new JdbcTemplate(source);
       System.out.println("DataSource = " + template.getDataSource());
       List records = template.queryForList("SELECT * FROM STUDENT");
       records.stream().forEach(data -> System.out.println("ROW = " + data));
   }

   /**
    * Will returns DataSource object for connection to the database.
    *
    * @return a DataSource.
    */
   private static DataSource getDataSource() {
       DriverManagerDataSource dataSource = new DriverManagerDataSource();
       dataSource.setDriverClassName(DataSourceDemo.DRIVER);
       dataSource.setUrl(DataSourceDemo.JDBC_URL);
       dataSource.setUsername(DataSourceDemo.USERNAME);
       dataSource.setPassword(DataSourceDemo.PASSWORD);
       return dataSource;
   }
}
Answer is