将数据库中的数据输入到JTable出错
/** To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package database_table;
import java.sql.*;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
/**
*
* @author Administrator
*/
class database extends JFrame {
JTable jt;
JScrollPane js;
Object data[][]=null;
Object head[] = {"用户名", "密码"};
public database() {
super("数据库实例");
this.connect();
this.setVisible(true);
this.setResizable(false);
this.setSize(400, 300);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private void connect() {
try {
int rows = 0, index = 0;
Connection con = DriverManager.getConnection("jdbc:odbc:mydatabase");
Statement cmd = con.createStatement();
ResultSet rs = cmd.executeQuery("select * from userlogin");
while (rs.next()) {
rows++;
}
data = new Object[rows][2];
rs.beforeFirst();//beforeFirst 不是将光标移到第一行吗?为什么这里会抛出异常??
while (rs.next()) {
data[index][0] = rs.getString(1);
data[index][1] = rs.getString(2);
index++;
}
} catch (SQLException ex) {
//Logger.getLogger(database.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("数据库异常!");
}
jt = new JTable(data, head);
js = new JScrollPane(jt);
this.setContentPane(js);
}
}
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
new database();
}
}
我的红色部分是取得表的行数,但是当执行到绿色部分是就抛出异常了,想问一下这个地方该怎么做?
如果有更好的方法请贴上代码一起研究研究!
----------------解决方案--------------------------------------------------------
问题解决了
Statement cmd = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);这个地方要这样改就好了。
当时还有就是拖动那个表格的列名是会把两列交换位置,怎么设置才能让他们固定下来
----------------解决方案--------------------------------------------------------