PreparedStatement是在数据库端防止SQL注入漏洞的SQL方法 这里演示了一些基本使用方法 同样使用Oracle数据库,之前已经手动建立了一张t_account表 数据库代码参见上一篇《JDBC连接数据库演示》
import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.util.Scanner;public class PreparedStatementTest { public static void main(String[] args) throws Exception { Scanner input = new Scanner(System.in); System.out.println("Please enter card id: "); int c = input.nextInt(); System.out.println("Please enter password: "); String p = input.next(); //1.加载驱动 Class.forName("oracle.jdbc.OracleDriver"); //2.获得数据库连接 String url = "jdbc:oracle:thin:@127.0.0.1:1521:XE"; String user = "hr"; String password = "hr"; Connection conn = DriverManager.getConnection(url,user,password); System.out.println(conn);//判断数据库连接是否成功 //3.准备SQL语句 String sql = "select * from t_account where card_id = ? and password = ?"; System.out.println(sql);//输出SQL语句 //4.PreparedStatement开始 //PreparedStatement--1.创建PreparedStatement PreparedStatement pstm = conn.prepareStatement(sql); //PreparedStatement--2.绑定参数 pstm.setInt(1, c); pstm.setString(2, p); //PreparedStatement--3.发送绑定参数至数据库 ResultSet rs = pstm.executeQuery();//查询 //long i = pstm.executeLargeUpdate();//增删改 //PreparedStatement结束 //5.判断查询结果是否为空 if(rs.next()){ System.out.println("Login success"); }else System.out.println("Login fail"); //6.释放资源 rs.close(); pstm.close(); conn.close(); }}