星之魔法团第三季:高手帮忙解答这则小程序的问题

来源:百度文库 编辑:高校问答 时间:2024/05/08 23:50:27
import javax.swing.table.*;
import java.awt.*;
import javax.swing.*;
import java.sql.*;

class table1 extends JFrame{
Object[][]cells;
String columns[]={"用户名","密码","邮箱","QQ"};
String url="jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=Student";
String user="sa";
String password="";
JTable table;
int i=0;
public table1(){
Container contentPane=this.getContentPane();
JPanel p=new JPanel();
try{
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
Connection con=DriverManager.getConnection(url,user,password);
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from userstate");
while(rs.next()){
cells[i]=new Object[4];
cells[i][0]=rs.getString(1);
cells[i][1]=rs.getString(2);
cells[i][2]=rs.getString(3);
cells[i][3]=rs.getString(4);
i++;
}
rs.close();
stmt.close();
con.close();
}catch(SQLException se){}
catch(Exception e){}
table=new JTable(cells,columns);
p.add(new JScrollPane(table));
contentPane.add(p);
setSize(new Dimension(400,400));
}
public static void main(String args[]){
table1 newFrame=new table1();
newFrame.show();
}
}
为何显示不出来表格
dos下显示异常
编译通过了,但是提示main nullpointerexception异常,jdbc肯定没问题

import javax.swing.table.*;
import java.awt.*;
import javax.swing.*;
import java.sql.*;

class table1 extends JFrame{
Object[][]cells=
{
{"Apples", "12345","5.00","8803"},
{"Oranges","45678","6.00","8802"},
{"Pears","78954","4.00","8801"},
{"Grapes","87654","2.00","8800"},

};
String[] columns={"用户名","密码","邮箱","QQ"};
String url="jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=Student";
String user="sa";
String password="";
JTable table;
int i=0;
public table1(){
Container contentPane=this.getContentPane();
JPanel p=new JPanel();
try{
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
Connection con=DriverManager.getConnection(url,user,password);
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from userstate");
/*while(rs.next())
{
cells[i]=new Object[4];
cells[i][0]="x";
cells[i][1]="2x";
cells[i][2]="3x";
cells[i][3]="4x";
i++;
}*/
rs.close();
stmt.close();
con.close();
}catch(SQLException se){}
catch(Exception e){}
table=new JTable(cells,columns);
p.add(new JScrollPane(table));
contentPane.add(p);
setSize(new Dimension(400,400));
}
public static void main(String args[]){
table1 newFrame=new table1();
newFrame.setVisible(true);
}
}
这样写就没有问题,所以问题出在你的sql那个地方,好好检查一下,看看连接数据库这个地方肯定有问题!

问题关键:有没有加入JDBC库?
其他不规范的地方:
1,开头请用package打包
2,类名开头字母请大写
3,show()方法已过时,请用setVisible(true)