Statement 接口基本介绍与使用
基本介绍
1.Statement对象,用于执行静态sqlyuju并返回其生成的结果的对象
2.在建立连接后,需要对数据库进行访问,执行命名或是SQL语句,可以通过
(1)Statement
[存在SQL注入风险,开发中不会使用]
(2)PrepareStatement
[预处理]
(3)CallableStatement
[存储过程]
3.== SQL注入==是利用某些系统没有对用户输入的数据进行充分的检查,而在用户输入数据中注入非法的SQL语句或命令,恶意攻击数据库。sql_injection.sql
4.要防范SQL注入,用PreparedStatement取代Statement就可以
应用实例
注意: 使用万能密码时,Scanner读入不能使用next() 方法,此时遇到空格/回车时会结束,而 nextLine()直到回撤才会结束。
代码展示:
package Jdbc.myjdbc;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;
import java.util.Scanner;
/**
* @author zq
* 演示statement的注入问题
*/
public class Statement_ {
public static void main(String[] args) throws IOException, ClassNotFoundException, SQLException {
//创建配置文件对象
Properties properties = new Properties();
//获取文件中的键值
properties.load(new FileInputStream("src\\Jdbc\\myjdbc\\mysql.properities"));
String url = properties.getProperty("url");
String user = properties.getProperty("user");
String password = properties.getProperty("password");
String driver = properties.getProperty("driver");
Class.forName(driver);
Connection connection = DriverManager.getConnection(url, user, password);
Statement statement = connection.createStatement();
String admin_user;
String admin_pwd;
Scanner scanner = new Scanner(System.in);
System.out.println("请输入用户名");
admin_user = scanner.nextLine();
System.out.println("请输入密码");
admin_pwd = scanner.nextLine();
//使用SQL语句
String sql = "select * from admin where name ='" +
admin_user+"' and pwd = '" + admin_pwd + "'";
ResultSet resultSet = statement.executeQuery(sql);
if (resultSet.next()){
System.out.println("登陆成功");
}else{
System.out.println("登陆失败");
}
resultSet.close();
statement.close();
connection.close();
}
}
结果展示:
输入万能密码后的结果