Statement or Preparedstatement, for what reason avoid using Statement

Asked

Viewed 291 times

1

What problems can happen if I use Statement instead of Preparedstatement on the JDBC connection to the database

//Code using Preparedstatement, setting query values through methods

    Connection con = null;
    PreparedStatement ps = null;
    ResultSet rs = null;
    String query = "SELECT * FROM exemplo WHERE coluna1 = ? AND coluna2 = ?";
    try {
        con = DBConnection.getConnection();
        ps = con.prepareStatement(query);

        ps.setString(1, valorExemplo1);
        ps.setString(2, valorExemplo2);
        rs = ps.executeQuery();

//Code using Statement, concatenating the values of the variables to the query

        Connection con = null;
        Statement stmt = null;
        ResultSet rs = null;
        String query = "SELECT * FROM exemplo WHERE coluna1 = '"+valorExemplo1+"'  
                        AND  coluna2 = '"+valorExemplo2+"';
        try{
            con = DBConnection.getConnection();
            stmt = con.createStatement();
            rs = stmt.executeQuery(query);
  • 1

    This serves to prevent attacks from SQL Injection <- this question is about C#, but the idea is the same

1 answer

1


Good Afternoon All right?

The difference is in speed, ease of maintenance and information security between objects.

When you use Statement, you have all the processing of this declaration to be processed in the bank, which takes a little longer, but it is not so clear with a low volume, the code is not so readable and you are passing your statement "all open".

"SELECT * FROM exemplo WHERE coluna1 = '"+valorExemplo1+"' AND  coluna2 = '"+valorExemplo2+"';

For someone to intercept your code, injecting SQL is easier, you’re more vulnerable.

When you use Preparedstatement, you have already prepared the entire statement, which gets faster to process in the bank, you have readability and a maintenance in the code, Since in most cases getters and setters are used and you have an exemption from this vulnerability (SQL injection), your SQL command is only "built" after, it makes interception difficult.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.