1. Preprocessing objects
(1) When using PreparedStatement preprocessing objects, it is recommended that all the actual parameters of each SQL statement be separated by commas ;
= "insertintovalues= conn.preparestatement (SQL)
(2) Execute SQL statement
int -- executes the INSERT Update DELETE statement. -- executes the SELECT statement. Execute -- Execute Select returns True to execute other statement returns false
(3) Setting the actual parameters
①void setxxx (int index, XXX xx) sets the specified parameter to the XX value of the given Java. When this value is sent to the database, the driver converts it to a SQL xxx type value;
SetString (2, "Home appliance") put a placeholder for the 2nd position in the SQL statement? Replace with actual parameters "Home appliances"
(4) Code Demo
1 Importjava.sql.Connection;2 ImportJava.sql.DriverManager;3 Importjava.sql.PreparedStatement;4 ImportJava.sql.ResultSet;5 ImportJava.util.Scanner;6 7 Public classJDBCDemo3 {8 Public Static voidMain (string[] args)throwsException {9Class.forName ("Com.mysql.jdbc.Driver");TenString url = "Jdbc:mysql://localhost:3306/mybase"; OneString username = "root"; AString password = "root"; -Connection con =drivermanager.getconnection (URL, username, password); -Scanner sc =NewScanner (system.in); theString user =sc.nextline (); -String pass =sc.nextline (); - - //Execute SQL statement, data table, query user name and password, if present, login successful, no login failed +String sql = "SELECT * from users WHERE username=?" and password=? "; - //Call the Connection interface method Preparestatement, get the implementation class for the Preparestatement interface + //method, the parameters in the SQL statement all take the question mark placeholder APreparedStatement PST =con.preparestatement (SQL); at System.out.println (PST); - //call the PST object Set method, set the parameter on the question mark placeholder -Pst.setobject (1, user); -Pst.setobject (2, pass); - - //invoke method, execute SQL, get result set inResultSet rs =pst.executequery (); - while(Rs.next ()) { toSystem.out.println (rs.getstring ("username") + "" ++ rs.getstring ("password")); - } the * rs.close (); $ pst.close ();Panax Notoginseng con.close (); - } the}
00310_ Preventing SQL injection