1

Approach 1 :

Connection connection=Connector.getConnection();
PreparedStatement ps1=connection.prepareStatement("insert into tbl_invtry(part_id,part_name)
                                                  values(?,?,)");
ps1.setString(1,action.getPart_id());
ps1.setString(2,action.getPart_name());

Approach 2 :

DAO dao = new DAOImpl(); //DB connection
String query="insert into tbl_entrp_proj(ASPECT_SRC_ID,PRNT_PROJ_ID)values('" + 
                                         project.getASPECT_SRC_ID() + "','" + 
                                         project.getPRNT_PROJ_ID() + "')";
boolean b = dao.insertQuery(query);  

Please suggest which is the best, and why. Thanks in advance.

Steve P.
  • 14,489
  • 8
  • 42
  • 72
Guru
  • 55
  • 7

2 Answers2

2

I would go for the 1st approach because:

  1. It is more efficient - PreparedStatement can be compiled and reused by the database.
  2. Security. When using a PreparedStatement, you don't need to worry about encoding and SQL injection.

However, I would consider a 3rd approach - using an ORM framework like Hibernate.

Amir Kost
  • 2,148
  • 1
  • 16
  • 30
2

As Ashwin and dasblinkenlight stated, SQL injection is the concern.

In Approach 1 you've used parameterized queries to escape any user input to prevent SQL injection, in Approach 2 you've trusted the user to provide values that are directly inserted into your database.

Keep in mind that SQL injected statements may not be a problem on insert, but upon select (or other queries ) could wreck havoc with your data and database.

Not using Approach one is irresponsible at best, and disastrous at worst because of these reasons.

For a secondary reason of why approach 1 is best, take a look at this question which discusses the performance benefits of prepared statements, and heavily emphasizes the importance of protecting against SQL injection.

Community
  • 1
  • 1
Robert H
  • 11,520
  • 18
  • 68
  • 110