javasql转义
使用预处理.估计%应该用转义字符..用预处理安全防止sql注入..具体方法如下:
//conn = DBUtil.getInstance().getConnection();这个是获取conn的一个方法
//DBUtil.getInstance().close(pstmt, conn);这个是我关闭pstmt conn的方法
//关键就是使用PreparedStatement 这个预处理。要导入包import java.sql.PreparedStatement;
public void addStudent(BufferedReader br){
String name = null;
String sex = null;
String age = null;
String id = creatId();
Connection conn =null;
PreparedStatement pstmt = null;
System.out.println("请输入学生相应的信息:");
try {
//从键盘输入学生名称
System.out.println("请您输入学生姓名 :");
name = br.readLine();
//从键盘输入性别
System.out.println("请您输入学生性别 :");
sex = br.readLine();
//从键盘输入年龄
System.out.println("请您输入学生年龄 :");
age = br.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// System.out.println(name + sex + age);
// insertStudent(name,sex,age);
conn = DBUtil.getInstance().getConnection();
//通过输出判断conn是否正确
// String sql = "insert into t_student(id,name,sex,age) values(111,"+"'"+name+"','"+sex+"',"+age+")";
String sql = "insert into t_student(id,name,sex,age) values(?,?,?,?)";
try {
pstmt=conn.prepareStatement(sql);
pstmt.setString(1, id);
pstmt.setString(2, name);
pstmt.setString(3, sex);
pstmt.setString(4, age);
pstmt.execute();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
DBUtil.getInstance().close(pstmt, conn);
System.out.println("记录插入成功");
}
如果还有疑问联系我:qq 6 0 3 051135