PreparedStatement for java Learning
When Prepared sees this word, preparation means that PreparedStatement is actually precompiled. So what is the difference with Statement?
PreparedStatemen has the following benefits:
1. prevent repeated compilation of SQL statements with similar structures
2. No worries about concatenating strings
3. Prevent SQL injection (concatenated strings may cause SQL Injection problems)
4. Pre-compiled SQL statements in the PreparedStatement object, with good performance
Instructor Niu talked about the knowledge of "SQL statement injection". In fact, this problem still exists in java, and PreparedStatement perfectly solves this problem.
In this way, I will add an instance in DRP to learn it together.
import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Timestamp;import java.util.ArrayList;import java.util.Date;import java.util.List;
/*** Add user * @ param User */public void addUser (user User) {String SQL = insert into t_user (user_id, user_name, password, contact_tel, email, create_date) + values (?, ?, ?, ?, ?, ?); // Insert new user Connection conn = null; // instantiate PreparedStatement and result set PreparedStatement pstmt = null; // instantiate PreparedStatement and result set try {conn = DbUtil. getConnection (); // obtain the SQL statement pstmt = conn. prepareStatement (SQL); // The role of pre-compilation is embodied in this. Pstmt. setString (1, user. getUserId (); // user Idpstmt. setString (2, user. getUserName (); // the user name pstmt. setString (3, user. getPassword (); // The User Password pstmt. setString (4, user. getContactTel (); // the user's phone number pstmt. setString (5, user. getEmail (); // user email // pstmt. setTimestamp (6, new Timestamp (System. currentTimeMillis (); pstmt. setTimestamp (6, new Timestamp (new date().gettime(~~~~pstmt.exe cuteUpdate ();} catch (SQLException e) {e. printStackTrace (); // handle exceptions} finally {DbUtil. close (pstmt); DbUtil. close (conn );}}This is only part of the code, but it details the usage of PreparedStatement. The underlying applications should be fixed knowledge. When you see more, you will not be flustered.