1. 没有ORM框架时的情况
让我们回顾下,之前没有ORM框架时,是如何使用JDBC操作数据库的。
1.1 查询,使用Statement,有被SQL注入攻击的危险
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection(dbURL, userName, userPwd);
String name="Bee' or '1'='1' -- "; //会被SQL注入攻击
String word="aaa";
String sql="select * from users where name='"+name+"' and word='"+word+"'";
Statement stmt = con.createStatement();
ResultSet rs =stmt.executeQuery(sql);
while(rs.next()){
//在此处获取结果. 手动封装成Javabean
System.out.println(rs.getString(2));
}
System.out.println("");
}catch(SQLException e){
System.out.println("have exception"+e.getMessage());
}
1.2 查询,使用PreparedStatement, 可以防止SQL注入攻击
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection(dbURL, userName, userPwd);
String sql="select * from users where name=? and word=?";
PreparedStatement stmt = con.prepareStatement(sql);
stmt.setString(1, "Bee' or '1'='1'");//防止SQL注入攻击
stmt.setString(2,"aaa");
ResultSet rs = stmt.executeQuery();
while(rs.next()){
//在此处获取结果. 手动封装成Javabean
System.out.println(rs.getString(2));
}
System.out.println("");
}catch(SQLException e){
System.out.println("have exception"+e.getMessage());
}
总结直接使用JDBC,存在的工作量或问题,主要有:
针对每个实体写一份dao操作文件,n个实体就要写n份。