简体   繁体   中英

Java - to - sql statement, variables in Insert into vs setString

What is the difference between these two statements, do they both work the same way, or does the first one work at all? Can I use variables after "Insert into"?

stmt = conn.prepareStatement("INSERT INTO treatment(CPR,Treatment,ID,TreatedOn) "+
"VALUES("+Cpr+Id+date.toString());

Where id , cpr are a string , int or other variable, bin my case it is a string ,

PreparedStatement insertStatement;

        insertStatement = connection.prepareStatement("INSERT INTO sep2.movies(title,length) "
                + "VALUES (?,?,?)");
        insertStatement.setString(1, Title);
        insertStatement.setInt(2, movie.getLength());

where Title is a string and getLength returns an int .

Which one of these should I use ?

I understand what setString does but do I have to use it?

Also I am inserting only elementary/non-object data types into Treatment . Does it make a difference? (I am using postgres if that matters)

And other important aspect of using bind variables, is that it improves the performance of the application. When you use bind variables, database server cache and optimize the query and improve the performance (respect to time and processing) of your application.

For example, When you use

insertStatement = connection.prepareStatement("INSERT INTO sep2.movies(title,length) "
        + "VALUES (?,?,?)");
insertStatement.setString(1, Title);
insertStatement.setInt(2, movie.getLength());

The statement is cashed inside database server and only the parameters are bind in the run time inside the database. This will improve performance significantly.

you can read Designing applications for performance and scalability An Oracle White Paper http://www.oracle.com/technetwork/database/performance/designing-applications-for-performa-131870.pdf

It is always a good practice that applications that execute SQL commands should neutralize any externally-provided values used in those commands. Failing in doing so could allow an attacker to include input that changes the query so that unintended commands are executed, or sensitive data is exposed ( SQL Injection ).

The first example (string concatenation) is not safe, because it is vulnerable to SQL Injection since malicious data can be concatenated to the query itself (not to mention that it can lead to syntax errors, etc).

The second case (where method such as PreparedStatement#setString are used) correctly uses parameterized queries by utilizing Java's PreparedStatement class, bind variables and the corresponding setString methods. Thus SQL Injection can be easily prevented (avoiding other problems such as the mentioned syntax errors).


Further readings:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM