源代码:
public class Test4 {
static Connection con;
static PreparedStatement sql; //声明预处理语句
static ResultSet res;
public Connection getConnection(){
try {
con = DBLink.connection(); //获取与数据库的连接
sql = con.prepareStatement("select * from EduData..student where SID = ?"); //预处理语句
sql.setString(1,"2005216007"); //设置参数
res = sql.executeQuery(); //执行预处理语句
//如果当前记录不是结果集中地最后一行,则进入循环体
while (res.next()) {
String SID = res.getString("SID"); //获取结果集中地指定值
String name = res.getString("Sname");
String sex = res.getString("Sex");
String date = res.getString("Brithday");
String ss = res.getString("Specialty");
System.out.print("学号:"+SID);
System.out.print(" 姓名:"+name);
System.out.print(" 性别:"+sex);
System.out.print(" 生日:"+date);
System.out.println(" 专业:"+ss);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return con;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Test4 tt = new Test4();
tt.getConnection();
}
}
运行时出现下面异常:
com.microsoft.sqlserver.jdbc.SQLServerException: 索引 1 超出范围。
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(Unknown Source)
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.setterGetParam(Unknown Source)
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.setString(Unknown Source)
at com.gem.lianxi.Test4.getConnection(Test4.java:19)
at com.gem.lianxi.Test4.main(Test4.java:45)
请问这是怎么回事?该怎么解决?什么原因?
解决方法找到一种:就是这样写:sql = con.prepareStatement("select * from EduData..student where SID = " + "?");
但是还是不清楚为什么要这样做?那样出错的原因是什么?