java中动态执行SQL语句报错:索引2超出范围,求大神指导~
报错:添加了1条记录到student表中com.microsoft.sqlserver.jdbc.SQLServerException: 索引 2 超出范围。
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(SQLServerException.java:170)
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.setterGetParam(SQLServerPreparedStatement.java:698)
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.setValue(SQLServerPreparedStatement.java:707)
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.setString(SQLServerPreparedStatement.java:1015)
at dblx.Sjk1_3.main(Sjk1_3.java:40)
package dblx;
import java.sql.*;
public class Sjk1_3 {
private static String driver="com.microsoft.sqlserver.jdbc.SQLServerDriver";
private static String url="jdbc:sqlserver://neverAgain\\neverAgain:1433;DatabaseName=Myschool";
private static String user="sa";
private static String password="111111";
public static void main(String[] args)
{
Connection conn=null;
PreparedStatement ps=null;
ResultSet rs=null;
String selectsql="select * from Student where Sex=?";
String insertsql="insert into Student(Sno,Sname,Sex,Sage)"+
"values(?,?,?,?);";
String updatesql="update Student set Sno='1410030014' where Sname=?";
String deletesql="delete from Student where Sno=?";
try{
Class.forName(driver);
conn=DriverManager.getConnection(url,user,password);
ps=conn.prepareStatement(selectsql);
ps.setString(1,"女");
rs=ps.executeQuery();
while(rs.next()){
String no=rs.getString("Sno");
String name=rs.getString("Sname");
String sex=rs.getString("Sex");
String age=rs.getString("Sage");
System.out.println(no+""+name+""+sex+""+age);
}
ps=conn.prepareStatement(insertsql);
ps.setString(1, "1410030006");
ps.setString(2, "李明");
ps.setString(3, "男");
ps.setString(4,"13");
int count=ps.executeUpdate();
System.out.println("添加了"+count+"条记录到student表中");
ps=conn.prepareStatement(updatesql);
ps.setString(2, "李四");
count=ps.executeUpdate();
System.out.println("更新了"+count+"条记录到student表中");
// ps=conn.prepareStatement(deletesql);
// ps.setString(1,"1410030001");
// count=ps.executeUpdate();
// System.out.println("删除了"+count+"条记录到student表中");
}
catch(Exception e){
e.printStackTrace();
}
finally{
try{
if(rs!=null)rs.close();
if(ps!=null)ps.close();
if(conn!=null)conn.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
}