[Microsoft][
SQLServer 2000 Driver for JDBC]Column index 6 is out of range.这是什么原因
代码如下:
package com.test1;
import java.util.Vector;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import java.sql.*;
public class test2 extends JFrame{
//用rowDate存放行数据
//用columnNames存放列名
Vector rowDate,columnName;
JTable jt=null;
JScrollPane jsp=null;
//定义链接数据库需要的东西
PreparedStatement ps=null;
Connection ct=null;
ResultSet rs=null;
public static void main(String[] args) {
// TODO Auto-generated method stub
test2 test22=new test2();
}
public test2(){
columnName=new Vector();
//设置列名
columnName.add("学号");
columnName.add("名字");
columnName.add("性别");
columnName.add("年龄");
columnName.add("籍贯");
columnName.add("系别");
rowDate=new Vector();
//rowDate可以存放多行
Vector hang=new Vector();
//从数据库中取出数据
try {
//加载驱动
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
//链接数据库
ct=DriverManager.getConnection
("jdbc:microsoft:sqlserver://127.0.0.1:1433;DatabseName=spdb1","test","123456");
ps=ct.prepareStatement("select stuId,stuName,stuSex,stuAge,stuJg,stuDept from stu");
rs=ps.executeQuery();
//循环取出
while(rs.next()){
hang.add(rs.getString(1));
hang.add(rs.getString(2));
hang.add(rs.getString(3));
hang.add(rs.getInt(4));
hang.add(rs.getString(6));
hang.add(rs.getString(7));
//加入到rowDate中
rowDate.add(hang);
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally{
try {
//关闭资源
if(rs!=null) rs.close();
if(ps!=null) ps.close();
if(ct!=null) ct.close();
} catch (
SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//初始化JTable
jt=new JTable(rowDate,columnName);
//初始化JSp JScrollpane
jsp=new JScrollPane(jt);
//将JSp放入到JFrame中去
this.add(jsp);
this.setSize(400,300);
this.setTitle("学生活动中心管理系统");
this.setLocation(400, 300);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
}
异常如下:
java.sql.SQLException: [Microsoft][SQLServer 2000 Driver for JDBC]Column index 6 is out of range.
at com.microsoft.jdbc.base.BaseExceptions.createException(Unknown Source)
at com.microsoft.jdbc.base.BaseExceptions.getException(Unknown Source)
at com.microsoft.jdbc.base.BaseResultSet.validateColumnIndex(Unknown Source)
at com.microsoft.jdbc.base.BaseResultSet.getString(Unknown Source)
at com.test1.test2.<init>(test2.java:54)
at com.test1.test2.main(test2.java:25)
------解决方案--------------------
你的ResultSet只查询得到6个字段值,但是你在程序当中调用了rs.getString(7),所以会报错