黑马程序员技术交流社区
标题:
关于PreparedStatement类防SQL注入问题?
[打印本页]
作者:
黄茂霖
时间:
2013-4-24 21:43
标题:
关于PreparedStatement类防SQL注入问题?
本帖最后由 shenqi 于 2013-4-24 21:44 编辑
package com.itcast.itheima;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class PreparedStatmentTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Connection ct = null;
ResultSet rs =null;
PreparedStatement ps = null;
try {
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
ct = DriverManager.getConnection
("jdbc:microsoft:sqlserver://127.0.0.1:1433;database=db_webApps", "sa", "999999");
//ps = ct.prepareStatement("select pass from tb_user where name = ?");
ps = ct.prepareStatement("select top ? * from tb_user where id not in(select top ?s id from tb_user)");
//select pass from tb_user where name = ? or 1 = 1
ps.setString(1, "6");
ps.setString(2, "3");
rs = ps.executeQuery();
while(rs.next()){
/* if("999999".equals(rs.getString(1))){
System.out.println("存在该账号");
}*/
System.out.println(rs.getString(1));
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
if(rs != null){
rs.close();
}
if(ps != null){
ps.close();
}
if(ct != null){
ct.close();
}
} catch (Exception e2) {
// TODO: handle exception
e2.printStackTrace();
}
}
}
}
复制代码
这是一个分页程序,为什么这样运行确报告SQL错误?
java.sql.SQLException: [Microsoft][SQLServer 2000 Driver for JDBC][SQLServer]第 1 行: '@P1' 附近有语法错误。
at com.microsoft.jdbc.base.BaseExceptions.createException(Unknown Source)
at com.microsoft.jdbc.base.BaseExceptions.getException(Unknown Source)
at com.microsoft.jdbc.sqlserver.tds.TDSRequest.processErrorToken(Unknown Source)
at com.microsoft.jdbc.sqlserver.tds.TDSRequest.processReplyToken(Unknown Source)
at com.microsoft.jdbc.sqlserver.tds.TDSRPCRequest.processReplyToken(Unknown Source)
at com.microsoft.jdbc.sqlserver.tds.TDSRequest.processReply(Unknown Source)
at com.microsoft.jdbc.sqlserver.SQLServerImplStatement.getNextResultType(Unknown Source)
at com.microsoft.jdbc.base.BaseStatement.commonTransitionToState(Unknown Source)
at com.microsoft.jdbc.base.BaseStatement.postImplExecute(Unknown Source)
at com.microsoft.jdbc.base.BasePreparedStatement.postImplExecute(Unknown Source)
at com.microsoft.jdbc.base.BaseStatement.commonExecute(Unknown Source)
at com.microsoft.jdbc.base.BaseStatement.executeQueryInternal(Unknown Source)
at com.microsoft.jdbc.base.BasePreparedStatement.executeQuery(Unknown Source)
at com.itcast.itheima.PreparedStatmentTest.main(PreparedStatmentTest.java:35)
复制代码
而我把SQL语句换成select pass from tb_user where name = ? 就没问题。这是怎么回事?这个问题纠结很久了!~
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2