#JDBC_解决SQL注入现象(必须使用SQL注入的需求)
package com.snailxq.jdbc;
import java.sql.*;
import java.util.Scanner;
public class JDBCTest08 {
public static void main(String[] args) {
// //用户在控制台输入desc就是降序,输入asc就是升序。
// //使用PreparedStatement出现 java.sql.SQLException: No value specified for parameter 1
// Scanner s=new Scanner(System.in);
// System.out.println("输入desc或者asc,desc表示降序,asc表示升序");
// System.out.print("请输入:");
// String keyWords =s.nextLine();
//
// //执行SQL编程6步
// Connection connection =null;
// PreparedStatement preparedStatement =null;
// ResultSet resultSet =null;
// try {
// //注册驱动
// Class.forName("com.mysql.jdbc.Driver");
// //获取连接
// connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/everours","root","333");
// //获取预编译数据库的连接对象
// String sql ="select ename from emp order by ename ?";
// preparedStatement =connection.prepareStatement(sql);
// //执行SQL
// resultSet =preparedStatement.executeQuery();
// while (resultSet.next()){
// System.out.println(resultSet.getString("ename"));
// }
// } catch (ClassNotFoundException e) {
// e.printStackTrace();
// } catch (SQLException e) {
// e.printStackTrace();
// } finally {
// //关闭资源
// if (resultSet != null){
// try {
// resultSet.close();
// } catch (SQLException e) {
// e.printStackTrace();
// }
// }
// if (preparedStatement!= null){
// try {
// preparedStatement.close();
// } catch (SQLException e) {
// e.printStackTrace();
// }
// }
// if (connection != null){
// try {
// connection.close();
// } catch (SQLException e) {
// e.printStackTrace();
// }
// }
//
// }
//用户在控制台输入desc就是降序,输入asc就是升序。
Scanner s=new Scanner(System.in);
System.out.println("输入desc或者asc,desc表示降序,asc表示升序");
System.out.print("请输入:");
String keyWords =s.nextLine();
//执行SQL编程6步
Connection connection =null;
Statement statement =null;
ResultSet resultSet =null;
try {
//注册驱动
Class.forName("com.mysql.jdbc.Driver");
//获取连接
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/everours","root","333");
//获取数据库的连接对象
statement =connection.createStatement();
//执行SQL
String sql ="select ename from emp order by ename "+ keyWords;
//执行SQL
resultSet = statement.executeQuery(sql);
while (resultSet.next()){
System.out.println(resultSet.getString("ename"));
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
//关闭资源
if (resultSet != null){
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (statement!= null){
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (connection != null){
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}