【上机作业】【java】2010.5.5 数据库与图形界面结合
简单的登陆界面
数据源名称:user_test
驱动程序 :SQL Server
默认数据库:test
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;//引入数据库的开发包
public class LoginV extends JFrame implements ActionListener
{ private JLabel JLb1;
private JLabel JLb2;
private JButton Ok_btn;
private JButton Cancel_btn;
private JTextField Jtfld1;
private JPasswordField Jtfld2;
private JFrame frame;
private Connection con;
private Statement stmt;
public LoginV()
{frame=new JFrame(“登陆”);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container content=frame.getContentPane();
content.setLayout(new GridLayout(3,2,20,20));
Font f1=new Font(“宋体”,Font.BOLD,28);
JLb1=new JLabel(“用户名:”);
JLb2=new JLabel(“密码:”);
Jtfld1=new JTextField();
Jtfld2=new JPasswordField();
JLb1.setFont(f1);
JLb2.setFont(f1);
Jtfld2.setFont(f1);
Jtfld1.setFont(f1);
Ok_btn=new JButton(“确定”);
Ok_btn.addActionListener(this);
Cancel_btn=new JButton(“取消”);
Cancel_btn.addActionListener(this);
Ok_btn.setFont(f1);
Cancel_btn.setFont(f1);
content.add(JLb1);
content.add(Jtfld1);
content.add(JLb2);
content.add(Jtfld2);
content.add(Ok_btn);
content.add(Cancel_btn);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setSize(300,200);
frame.setVisible(true);
}
public void showUser()
{Connection cn;
PreparedStatement ps;
ResultSet rs;
try{//加载数据库的驱动程序
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
//使用数据库连接串建立数据库连接
String url=”jdbc:odbc:user_test”;//student数据源
cn=DriverManager.getConnection(url,”sa”,””);
//生成语句对象
String sql=”select * from user_id where id=? and password=?”;
ps=cn.prepareStatement(sql);
ps.setString(1,Jtfld1.getText());
ps.setString(2,Jtfld2.getText());
//生成结果集
rs=ps.executeQuery() ;
//遍历结果集
if(rs.next())//记录指针
{
JOptionPane.showMessageDialog(null,”正确”,”提示”,JOptionPane.INFORMATION_MESSAGE);
}
else
{
JOptionPane.showMessageDialog(null,”非法用户”,”提示”,JOptionPane.INFORMATION_MESSAGE);
}
}catch(ClassNotFoundException e)
{
}
catch(SQLException e1)
{
}
}
public void actionPerformed(ActionEvent e)
{
JButton b=(JButton)e.getSource();
if(b==Ok_btn){
showUser();
}
if(b==Cancel_btn){
System.exit(0);
}
}
public static void main(String[]args)
{new LoginV();
}
}