连接 数据库

来源:互联网 发布:maya软件配置要求 编辑:程序博客网 时间:2024/06/05 01:26

 已登陆界面为例

先建立源包,创建数据库,统一调用

public class DBConnection {
    private static Connection con;
    
    public static Connection getCon(){

        try {

        //加载驱动

            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
          // 获取链接
            con=DriverManager.getConnection("jdbc:sqlserver://localhost:1433;DatabaseName = selectivedb", "sa", 
"321");
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(DBConnection.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            Logger.getLogger(DBConnection.class.getName()).log(Level.SEVERE, null, ex);
        }
        return con;
    
    
    }
    //关闭数据库
    public void con(){
        try {
            con.close();
        } catch (SQLException ex) {
            Logger.getLogger(DBConnection.class.getName()).log(Level.SEVERE, null, ex);
        }
}
}

  private void txtUserActionPerformed(java.awt.event.ActionEvent evt) {                                        
        // TODO add your handling code here:
    }                                       


    private void btnLoginActionPerformed(java.awt.event.ActionEvent evt) {                                         
         try {
        DBConnection db=new   DBConnection();
       Connection con   =   DBConnection.getCon(); 
       //获得单行文本信息
       String user=this.txtUser.getText();
       String pwd=new String(this.txtPassword.getPassword());
       if(con!=null){
            if(this.rdoManager.isSelected()){
              
            PreparedStatement ps=con.prepareStatement("select *from t_manager where sysaccount=? and Syspassword=? ");
            ps.setString(1, user);
            ps.setString(2, pwd);
            ResultSet rs=ps.executeQuery();
            if(rs.next()){
                JOptionPane.showMessageDialog(this,"欢迎进入选课系统");
                this.dispose();
             //跳转界面  SelectiveMainFrame 
            SelectiveMainFrame smf=new  SelectiveMainFrame();
            this.setVisible(false);
            smf.setVisible(true);
            }
            else{


             JOptionPane.showMessageDialog(this,"登录失败,请重新登录");
            LoginFrame lg=new    LoginFrame();
            lg.setVisible(true);
            
            }      
           
            }
         
  if(this.rdoTeacher.isSelected()){
 
               JOptionPane.showMessageDialog(this,"登录失败,请重新登录");
               LoginFrame lg=new    LoginFrame();
                  lg.setVisible(true);
            }
       
       if(this.rdoStudent.isSelected()){
 
               JOptionPane.showMessageDialog(this,"登录失败,请重新登录");
               LoginFrame lg=new    LoginFrame();
                  lg.setVisible(true);
            }
       
       }
       
       } catch (SQLException ex) {
               Logger.getLogger(LoginFrame.class.getName()).log(Level.SEVERE, null, ex);
           }
    } 




0 0