怎么用按钮连接数据库并显示这是我写的代码,我想输入了数据库的用户名&密码后,点击按钮可以连接数据库,并显示出来,请各位大哥帮帮忙啊,小弟急啊!!!!
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.sql.*;
class namepassDB extends JFrame{
static windowsevent we=new windowsevent();
static JLabel l1=new JLabel("username:",JLabel.LEFT);
static JLabel l2=new JLabel("password:",JLabel.LEFT);
static JButton jb=new JButton("OK");
void bulidConstraints(GridBagConstraints gbc,int gx,int gy,int gw,int gh,int wx,int wy){
gbc.gridx=gx;
gbc.gridy=gy;
gbc.gridheight=gh;
gbc.gridwidth=gw;
gbc.weightx=wx;
gbc.weighty=wy;
}
public namepassDB(){
super("username and password");
setSize(290,110);
GridBagLayout gridbag=new GridBagLayout();
GridBagConstraints Constraints=new GridBagConstraints();
JPanel pane=new JPanel();
pane.setLayout(gridbag);
bulidConstraints(Constraints,0,0,1,1,10,40);
Constraints.fill=GridBagConstraints.NONE;
Constraints.anchor=GridBagConstraints.EAST;
gridbag.setConstraints(l1,Constraints);
pane.add(l1);
bulidConstraints(Constraints,1,0,1,1,90,0);
Constraints.fill=GridBagConstraints.HORIZONTAL;
JTextField jtf=new JTextField();
gridbag.setConstraints(jtf,Constraints);
pane.add(jtf);
bulidConstraints(Constraints,0,1,1,1,0,40);
Constraints.fill=GridBagConstraints.NONE;
Constraints.anchor=GridBagConstraints.EAST;
gridbag.setConstraints(l2,Constraints);
pane.add(l2);
bulidConstraints(Constraints,1,1,1,1,0,0);
Constraints.fill=GridBagConstraints.HORIZONTAL;
JPasswordField jpf=new JPasswordField();
jpf.setEchoChar('*');
gridbag.setConstraints(jpf,Constraints);
pane.add(jpf);
bulidConstraints(Constraints,0,2,2,1,0,20);
Constraints.fill=GridBagConstraints.NONE;
Constraints.anchor=GridBagConstraints.CENTER;
gridbag.setConstraints(jb,Constraints);
pane.add(jb);
setContentPane(pane);
}
public static void main(String args[]){
namepassDB f=new namepassDB();
f.addWindowListener(we);
f.show();
try{connect();}
catch(Exception e4){System.out.println(e4.toString());}
}
static class windowsevent extends WindowAdapter{
public void windowclosing(WindowEvent e){
System.exit(0);
}
}
public void mouseClicked(MouseEvent e1){
try{connect();}
catch(Exception e5){System.out.println(e5.toString());}
}
public static void connect() throws SQLException,ClassNotFoundException{
Connection conn;
Statement stmt;
ResultSet rs;
String username=l1.getText();
String password=l2.getText();
try{Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");}
catch(ClassNotFoundException e2)
{System.out.println(e2.toString());}
try{conn=DriverManager.getConnection("jdbc:odbc:student",username,password);
stmt=conn.createStatement();
rs=stmt.executeQuery("select * from students");
while(rs.next())
{
System.out.print(rs.getString(1)+" ");
System.out.print(rs.getString(2)+" ");
System.out.print(rs.getString(3)+" ");
System.out.print(rs.getString(4)+" ");
System.out.println(rs.getString(5));
System.out.println();
}
}
catch(SQLException e3){System.out.println(e3.toString());}
}
}