package jdbc; import java.sql.*; import java.util.Scanner; public class HomeWork { /* Test1.java 输入老师的姓名,查询该老师的 姓名,年龄,职称,工资 */ public static void main(String[] args) { try (Connection connection = DBUtil.getConnection();){ Statement statement = connection.createStatement(); Scanner scanner = new Scanner(System.in); System.out.println("请输入老师的姓名:"); String username = scanner.nextLine(); String sql = "SELECT name,age,title,salary FROM teacher WHERE teacher='"+username+"'"; ResultSet resultSet = statement.executeQuery(sql); while (resultSet.next()){ String name = resultSet.getString("name"); int age = resultSet.getInt("age"); String title = resultSet.getString("title"); int salary = resultSet.getInt("salary"); System.out.println(""+name+","+age+","+title+","+salary); } } catch ( SQLException e) { e.printStackTrace(); } } }改正该代码
时间: 2024-02-14 14:15:48 浏览: 69
这段代码存在SQL注入的安全隐患,应该使用PreparedStatement或其他方式来防止注入攻击。以下是改正后的代码:
```
package jdbc;
import java.sql.*;
import java.util.Scanner;
public class HomeWork {
/*
* Test1.java 输入老师的姓名,查询该老师的 姓名,年龄,职称,工资
*/
public static void main(String[] args) {
try (Connection connection = DBUtil.getConnection();
PreparedStatement ps = connection.prepareStatement(
"SELECT name, age, title, salary FROM teacher WHERE teacher=?");) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入老师的姓名:");
String username = scanner.nextLine();
ps.setString(1, username);
ResultSet resultSet = ps.executeQuery();
while (resultSet.next()) {
String name = resultSet.getString("name");
int age = resultSet.getInt("age");
String title = resultSet.getString("title");
int salary = resultSet.getInt("salary");
System.out.println("" + name + "," + age + "," + title + "," + salary);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
```
改正后的代码使用了PreparedStatement,将用户输入的参数设置到占位符中,防止了SQL注入攻击。
阅读全文