How do I insert a new record into database table?
Category: org.springframework.jdbc, viewed: 1752 time(s).
The following example show you how to use the Spring's JdbcTemplate class to insert a record into database.
package org.kodejava.example.spring.jdbc;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import javax.sql.DataSource;
import java.sql.Types;
public class SpringJdbcInsertDemo {
private static final String sql = "INSERT INTO students (first_name, last_name) VALUES (?, ?)";
private DataSource dataSource;
public SpringJdbcInsertDemo(DataSource dataSource) {
this.dataSource = dataSource;
}
public void saveStudent(String firstName, String lastName) {
//
// Creates an instance of JdbcTemplate and passes a connection
// to the database.
//
JdbcTemplate template = new JdbcTemplate(this.dataSource);
//
// Defines the query arguments and the corresponding SQL types
// of the arguments.
//
Object[] params = new Object[] {firstName, lastName};
int[] types = new int[] {Types.VARCHAR, Types.VARCHAR};
//
// Calls JdbcTemplate.update() methods to create a new record
// in the students table. The update method in general will
// return number of row / rows processed by the executed query
//
int row = template.update(sql, params, types);
System.out.println(row + " row inserted.");
}
private static DriverManagerDataSource getDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost/kodejava");
dataSource.setUsername("root");
dataSource.setPassword("");
return dataSource;
}
public static void main(String[] args) {
DataSource dataSource = getDataSource();
SpringJdbcInsertDemo demo = new SpringJdbcInsertDemo(dataSource);
demo.saveStudent("Paul", "Allen");
demo.saveStudent("John", "Gecko");
}
}
Download Hundreds of Complimentary Industry Resources
Get hundreds of popular Industry magazines, white papers, webinars, podcasts, and more;
all available at no cost to you. With more than 600 complimentary offers, you'll find
plenty of titles to suit your professional interests and needs.
Click Here and Sign up today!