1 //preparedStatement 预编译SQL语句并执行:防止SQL注入
2
3 //实现简单的用户登录
4 import java.sql.Connection;
5 import java.sql.DriverManager;
6 import java.sql.ResultSet;
7 import java.sql.Statement;
8 import java.util.ArrayList;
9
10 public class UserLogin {
11 public static void main(String[] args) throws Exception {
12 //1.注册驱动
13 Class.forName("com.mysql.cj.jdbc.Driver");
14
15 //2.获取连接
16 String url = "jdbc:mysql://127.0.0.1:3306/db1";
17 String username = "root";
18 String password = "1234";
19 Connection conn = DriverManager.getConnection(url,username,password);
20
21 //接受用户输入的账号和密码
22 String name = "zhangsan";
23 String pwd = "123";
24
25 String sql = "select * from tb_user where username = '"+name+"' and password = '"+pwd+"'";
26
27 //获取stmt对象
28 Statement stmt = conn.createStatement();
29
30 //执行sql语句
31 ResultSet rs = stmt.executeQuery(sql);
32
33 if(rs.next()){
34 System.out.println("登陆成功~");
35 }
36 else{
37 System.out.println("登陆失败~");
38 }
39
40 //释放资源
41 rs.close();
42 stmt.close();
43 conn.close();
44 }
45
46 }
1 /*preparedStatement 的使用
2
3 1.获取PreparedStatement对象,参数用 ?替代。
4 String sql = "select * from tb_user where username = ? and password = ?"
5 通过connection对象获取,并传入相应的sql语句
6 PreparedStatement pstmt = conn.prepareStatement();
7
8 2.设置参数值
9 PreparedStatement对象:setXxx(参数1,参数2);
10 xxx:数据类型 参数1:?的位置编号,从1开始 参数2:?的值
11
12 3.执行SQL,不需要再传递值
13 excuteUpdate();或
14 excuteQuerry();
15 */
16
17
18 import java.sql.Connection;
19 import java.sql.DriverManager;
20 import java.sql.PreparedStatement;
21 import java.sql.ResultSet;
22
23 public class PStatement {
24 public static void main(String[] args) throws Exception {
25 //1.注册驱动
26 Class.forName("com.mysql.cj.jdbc.Driver");
27 //2.获取连接
28 String url = "jdbc:mysql://127.0.0.1:3306/db1";
29 String username = "root";
30 String password = "1234";
31 Connection conn = DriverManager.getConnection(url,username,password);
32
33 String name = "zhangsan";
34 String pwd = "123";
35
36 String sql = "select * from tb_user where username = ? and password = ?";
37
38 PreparedStatement pstmt = conn.prepareStatement(sql);
39 pstmt.setString(1,name);
40 pstmt.setString(2,pwd);
41
42 ResultSet rs = pstmt.executeQuery();
43
44 if(rs.next()){
45 System.out.println("登陆成功~");
46 }
47 else{
48 System.out.println("登陆失败~");
49 }
50
51 //释放资源
52 rs.close();
53 pstmt.close();
54 conn.close();
55 }
56
57 }