提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
一、初试
用到了上次先自己写的类
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;
public class Testlogin {
//登陆方法
public boolean login(String username, String password) {
Connection connection = null;
Statement st = null;
ResultSet rs = null;
if (username == null || password == null) {
return false;
}
//连接数据库
try {
connection = JDBCutils.connection();
String sql = "select * from user where username = '" + username + "' and password = '" + password + "'";
st = connection.createStatement();
rs = st.executeQuery(sql);
return rs.next();
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
JDBCutils.close(st,connection,rs);
}
return false;
}
public static void main(String[] args) {
//1.键盘录入
Scanner scanner = new Scanner(System.in);
System.out.println("请输入用户名:");
String username = scanner.nextLine();
System.out.println("请输入密码:");
String password = scanner.nextLine();
boolean flag = new Testlogin().login(username, password);
if(flag){
System.out.println("登陆成功");
}
else {
System.out.println("用户名或密码错误");
}
}
}
二、debug—sql注入问题
上面写的代码会出现以下的bug!!!
当初的sql判断登陆语句
select * from user where username = '" + username + "' and password = '" + password + "'
等价于
select * from user where username = 'adfafadfa' and password = 'a' or 'a' = 'a'
神奇的一幕出现了
sql注入:在拼接sql时,有一些sql的特殊关键字参与字符串的拼接,会造成安全性的问题
解决方法:使用PreparedStatement对象来解决
Statement产生的是静态的sql
PrepareStatement产生的是预编译的的sql
预编译的sql:参数使用?作为占位符
步骤:
1.导入驱动jar包
2.注册驱动
3.获取数据库连接对象 Connection
4.定义sql:
**注意:
sql的参数使用?作为占位符
select * from user where username = ? and password = ?;
5.获取执行sql语句的对象 PrepareStatement Connection.prepareStatement(String sql)
6.给 ?赋值
****方法:setXxx(参数1,参数2)
*参数1:?的编号 从1 开始
*参数2:?问号的值
7.获取sql,接受返回结果
8.处理结果
9.释放资源
修改
import java.sql.*;
import java.util.Scanner;
public class Testloginplus {
public boolean login(String username, String password) {
Connection connection = null;
PreparedStatement psst = null;
ResultSet rs = null;
if (username == null || password == null) {
return false;
}
//连接数据库
try {
connection = JDBCutils.connection();
String sql = "select * from user where username = ? and password = ?";
psst = connection.prepareStatement(sql);
psst.setString(1,username);
psst.setString(2,password);
rs = psst.executeQuery();
return rs.next();
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
JDBCutils.close(psst,connection,rs);
}
return false;
}
public static void main(String[] args) {
//1.键盘录入
Scanner scanner = new Scanner(System.in);
System.out.println("请输入用户名:");
String username = scanner.nextLine();
System.out.println("请输入密码:");
String password = scanner.nextLine();
boolean flag = new Testloginplus().login(username, password);
if(flag){
System.out.println("登陆成功");
}
else {
System.out.println("用户名或密码错误");
}
}
}
总结
后期都会使用PrepareStatement 而不适用 Statement
原因
1.可以防止SQL注入
2.效率更高