top of page

Write Sql query after connection in java



After having successful connection with MySql in SpringBoot project. You can use below steps to write your own query for CRUD operation in java.


  1. Write your query

Your Query can be of type select, insert, update and delete.

Let's start with select query. In select you get single or multiple columns from database. Let's take case of single column from database.


eg. select column_name from table_name where condition_ limit 1;


String sql = "select column_name from table_name where condition_ limit 1";

2. Make reference of JdbcTemplate

@Autowired
JdbcTemplate jdbcTemplate;

3. Call jdbcTemplate methods

JdbcTemplate having different overloaded methods like queryForObject, query etc.

If your query requires only one field and will get only one value then you can use queryForObject method. It will two parameter:

a) query

b) key of query



eg1: String sql = "select stu_name from student where stu_roll = "+ student_roll +" limit 1";
String studentName = jdbcTemplate.query(sql, String.class);

eg2: 
String sql = "select stu_name, stu_class, stu_add, stu_age from student where stu_roll = ? limit 1";
String List<Student> student_details = jdbcTemplate.query(sql, new StudentMapper(), request.getStudentRollNo());
// here Student Mapper is defined or you can directly iterate it using sql row set.
OR
String sql = "select stu_name, stu_class, stu_add, stu_age from student where stu_roll = ? limit 1";
SqlRowSet rs = jdbcTemplate.query(sql, request.getStudentRollNo());
List<Student> studentDetails = new ArrayList<Student>();
while(rs.next()){
       studentDetails.setName(rs.getString("stu_name"));
       studentDetails.setClass(rs.getString("stu_class"));
       studentDetails.setAdd(rs.setString("stu_add"));
       studentDetails.setAge(rs.getString("stu_age"));

} 




Comments


bottom of page