天天看点

PreparedStatement 的用法 | 学习笔记

开发者学堂课程【JDBC数据库开发入门:PreparedStatement 的用法】学习笔记,与课程紧密联系,让用户快速学习知识。

课程地址:

https://developer.aliyun.com/learning/course/29/detail/634

PreparedStatement 的用法

内容介绍

一、PreparedStatement 的强大之处

二、PreparedStatement 防 SQL 攻击

三、查询数据库

四、得到 connection

五、如何得到 Preparedstatement 对象

一、PreparedStatement 的强大之处

1.防 SQL 攻击

2.提高代码的可读性、可维护性

3.提高效率!

二、PreparedStatement防SQL攻击

1.登录

2.使用 username 和 password 去查询数据

3.若查出结果集说明正确!返回 true

4.若查出不出结果,说明用户名或密码错误,返回 false。

三、查询数据库

1.得到 connection

2.得到 statement

3.得到 Resultset

4.对 Resultset 进行判断:rs.next() 返回的是什么,就返回什么

四、得到 connection

(1)准备四大参数

String driverclassName = "com.mysql.jdbc.Driver";

String url = jdbc:mysql : // localhost : 3306/mnydb3";

String mysqlUsername = "root";

String mysqlPassword = "123";

(2)加载驱动类

Class.forName (driverclassName) ;

(3)得到 Connection

connection con = DriverManager.getConnection(url,mysqlusername,mysqlPasswrd)

(4)得到 Statement

Statement stmt =con.createstatement ();

(5)给出sql语句,调用stmt的executeQuery( ),得到Resultset

String sql = "select  * from t_user where username=" +username+" and password="+password+";system.out.println (sql);

Reaultset rs = stmt-executeQuery (sql);

return rs.next();

@Test

public void fun1()  throws Exception {

//select * from t_user where username='a' or 'a'='a iand password='a' or 'a'='a'

String username ="a' or 'a'='a";

String password ="a' or 'a'='a";

boolean bool = login ( username,password);

system.out.println (bool) ;}

 1.给出 SQL 模板:所有的参数使用?来替代

string sql = "select * from t_user where username=? and password=?" ;

2.调用 Connection 方法,得到 PreparaedStatement

PreparedStatement pstmt = con.preparcstatoment(aql);

3.调用pstmt的setXxx()系列方法 sql 模板中的?赋值!

为参数赋值

Pstmt.setString (1. username) ;//给第1个问号赋值,值为 username

pstmt.setstring (2,password) ; //给第2个问号赋值,值为 password

pstmt.setstring (3.“Xxx");

Resultset rs = pstmt.executeQuery( );//调用查询方法,向数据库发送查询语句

4.调用 pstmt 的 executeUpdate[) 或 executeQuery(),但它的方法都没有参数。