Use PreparedStatement in Java
In batches and applications that require DB connection, in most cases, the following classes are used to implement the connection process.
--java.sql.Connection class
--java.sql.Statement class
--java.sql.ResultSet class
But lately, it seems to be popular to use the java.sql.PreparedStatement class instead of the Statement class.
I will write down the reason.
Reason
- Measures against SQL injection
- As the name suggests, SQL is cached in the DB, so if you repeatedly issue the same SQL statement, the processing speed will be faster.
How to use
How to use it compared to the Statement class.
For Statement class
- Get an object of Statement class.
You can get it with the object .createStatement () of the Connection class.
- Execute the SQL statement using the Statement class object.
It can be executed with the Statement class object .execute ().
Connection con = DriverManager(hoge,hoge,hoge);
String sql = "select name from hogeData where id = '1'";
Statement st = con.createStatement(sql);
st.execute();
For PreparedStatement class
- Replace the value of the SQL statement you want to execute with?. At that time, it is not necessary to enclose it in a single quote.
- Get an object of PreparedStaetment class.
You can get it with the object .preparedStatement () of the Connection class. Pass the SQL statement as an argument.
- Insert a value into? In the object .setHoge () of the PreparedStatement class. At that time, setInt () for integer type, and setString () for string type value.
In the argument, specify the position of?. If it is the first? From? On the left side of the SQL statement, pass 1 as the first argument and the value you want to insert as the second argument.
- It can be executed by the object .executeQuery () or .executeUpdate () of the PreparedStatement class.
The method used depends on the presence or absence of the returned ResultSet.
Connection con = DriverManager(hoge,hoge,hoge);
String sql = "select name from hogeData where id = ?";
Statement st = con.preparedStatement(sql);
st.setInt(1, 1);
ResultSet rs = st.executeQuery();
If you want to dig deeper into why you should use it, read below.
(I will add it later)