[求助]连接数据库(初级)
下面的代码是从.mdb读出数据.然后显示在表格.有点问题,请教一下.在
for(int i = 0; i < data.length; i++)
{
data[i][0]=rs.getString(1);
data[i][1]=rs.getString(2);
data[i][2]=rs.getDate(3);
data[i][3]=rs.getFloat("数学");
data[i][4]=rs.getFloat("物理");
data[i][5]=rs.getFloat("英语");
}
中,用断点调式,可以看到,当i == 1会产生异常
如果把: i < data.length 改为: i < 1.则可以输出最后一行(为什么不是第一行?)
这是什么问题呢?要怎么弄才能正确显示呢?小弟先谢过了~~~
附:数据文件.
import java.sql.*;
import java.awt.*;
import javax.swing.*;
class JTable1 extends JFrame
{
JPanel cp = new JPanel();
JTable jtable1;
JScrollPane jscrp1 = new JScrollPane();
public JTable1()
{
cp = (JPanel)this.getContentPane();
this.setTitle("student");
this.setSize(500, 200);
cp.setLayout(new FlowLayout());
Connection con;
Statement sql;
ResultSet rs;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
}
catch (java.lang.ClassNotFoundException e)
{ System.out.println(" 打不开文件!"); }
try {
con= DriverManager.getConnection("jdbc:odbc:st","meteor","12345");
sql=con.createStatement();
rs=sql.executeQuery("SELECT * FROM result");
Object data[][] = new Object[3][6];
Object columnNames[] = {"学号","姓名","出生日期","数学","物理","英语"};
while(rs.next())
{
for(int i = 0; i < data.length; i++)
{
data[i][0]=rs.getString(1);
data[i][1]=rs.getString(2);
data[i][2]=rs.getDate(3);
data[i][3]=rs.getFloat("数学");
data[i][4]=rs.getFloat("物理");
data[i][5]=rs.getFloat("英语");
}
}
jtable1 = new JTable(data,columnNames);
jtable1.setRowHeight(20);
jscrp1.getViewport().add(jtable1);
cp.add(jscrp1);
con.close();
}
catch (SQLException el)
{ System.out.println(" 打开了文件,但没能显示数据!"); }
}
}
public class JAVADB
{
public static void main(String args[])
{
JTable1 JTable1 = new JTable1();
JTable1.setVisible(true);
}
}
student.rar
(7.33 KB)