1. 程式人生 > >資料庫簡單操作—註冊和登入例項

資料庫簡單操作—註冊和登入例項

  本例是建立使用者註冊和登入的資料庫操作,通過Swing元件實現註冊和登入介面的實現。

註冊

功能實現

註冊實現:
這裡寫圖片描述

判斷使用者名稱輸入是否合法:
這裡寫圖片描述

判斷密碼輸入是否合法:
這裡寫圖片描述

判斷兩次密碼輸入是否一致:
這裡寫圖片描述

註冊程式碼

//SQLManager類
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

//採用單例設計模式
public class SQLManager {
    private
Statement statement; //獲得statement public Statement getStatement() { return statement; } //返回statement public void setStatement(Statement statement) { this.statement = statement; } private static SQLManager manager; private SQLManager() { //連線資料庫的驅動
String driver = "com.mysql.jdbc.Driver"; //指向資料庫訪問地址 String url = "jdbc:mysql://localhost:3306/clazz"; //資料庫的使用者名稱 String user = "root"; //資料庫使用者密碼 String password = "123456"; try { //載入驅動
Class.forName(driver); //與資料庫建立連線 Connection conn = DriverManager.getConnection(url,user, password); if(!conn.isClosed()){ //建立資料庫操作類 statement = conn.createStatement(); }else{ System.out.println("請開啟資料庫!"); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } } /** * 建立該類的物件 * @return 返回SQLManager物件。 */ public static synchronized SQLManager newInstance(){ if(manager==null){ manager = new SQLManager(); } return manager; } }
//登入介面
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.awt.event.ActionEvent;

public class MySQL extends JFrame {

    private JPanel contentPane;
    private JTextField textFieldUserName;
    private JTextField textFieldPassword;
    private JTextField textFieldPasswordAgain;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    MySQL frame = new MySQL();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public MySQL() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 453, 395);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);

        textFieldUserName = new JTextField();
        textFieldUserName.setBounds(125, 77, 133, 21);
        contentPane.add(textFieldUserName);
        textFieldUserName.setColumns(10);

        JLabel lblNewLabelUser = new JLabel("使用者名稱:");
        lblNewLabelUser.setBounds(40, 80, 54, 15);
        contentPane.add(lblNewLabelUser);

        textFieldPassword = new JTextField();
        textFieldPassword.setBounds(125, 120, 133, 21);
        contentPane.add(textFieldPassword);
        textFieldPassword.setColumns(10);

        JLabel lblNewLabelPassword = new JLabel("密碼:");
        lblNewLabelPassword.setBounds(40, 123, 54, 15);
        contentPane.add(lblNewLabelPassword);

        textFieldPasswordAgain = new JTextField();
        textFieldPasswordAgain.setBounds(125, 175, 133, 21);
        contentPane.add(textFieldPasswordAgain);
        textFieldPasswordAgain.setColumns(10);

        JLabel lblNewLabelPasswordAgain = new JLabel("確認密碼:");
        lblNewLabelPasswordAgain.setBounds(40, 178, 75, 15);
        contentPane.add(lblNewLabelPasswordAgain);

        JButton btnNewButton = new JButton("提交");
        btnNewButton.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                //建立一個manager物件。
                SQLManager manager = SQLManager.newInstance();
                Statement statement = manager.getStatement();

                String userName = textFieldUserName.getText();
                //正則表示式判斷使用者名稱是否合法
                Pattern p_userName = Pattern.compile("^\\w+$");
                Matcher m_userName = p_userName.matcher(userName);
                boolean b_userName = m_userName.matches();


                String password = textFieldPassword.getText();
                //正則表示式判斷密碼是否合法
                Pattern p_password = Pattern.compile("^\\w+$");
                Matcher m_password = p_password.matcher(password);
                boolean b_password = m_password.matches();


                String passwordAgain = textFieldPasswordAgain.getText();
                //正則表示式判斷密碼是否合法
                Pattern p_passwordAgain = Pattern.compile("^\\w+$");
                Matcher m_passwordAgain = p_passwordAgain.matcher(passwordAgain);
                boolean b_passwordAgain = m_passwordAgain.matches();    
                if(b_userName){
                    System.out.println("輸入的使用者名稱合法!");
                    label_user.setText("");
                    if(b_password){
                        System.out.println("輸入的密碼合法!"); 
                        label_password.setText("");
                        if(b_passwordAgain){
                            System.out.println("輸入的密碼合法!");
                            label_passwordAgain.setText("");
                            try {
                                //判斷該使用者是否存在
                                String select ="select count(*) from user where name= '"+userName+"'";
                                ResultSet set =statement.executeQuery(select);
                                set.first();
                                int num = set.getInt(1);
                                if(num>0){
                                    System.out.println("該使用者已經存在!");
                                }else{
                                    if(passwordAgain.equals(password))
                                    {
                                    String insert = "insert into user(name, password) values('"+userName+"','"+password+"')";
                                    statement.execute(insert);
                                    System.out.println("使用者註冊成功!");
                                    textFieldUserName.setText("");
                                    textFieldPassword.setText("");
                                    textFieldPasswordAgain.setText("");
                                    }
                                    else{
                                        System.out.println("輸入的兩次密碼不一致!,請重新輸入……");
                                    }

                                }

                            } catch (SQLException e1) {
                                e1.printStackTrace();
                            }

                        }else{
                            String warning_passwordAgain = "輸入的密碼不合法!";
                            System.out.println(warning_passwordAgain);
                            label_passwordAgain.setText(warning_passwordAgain);
                            textFieldPasswordAgain.setText("");
                        }               
                    }else{
                        String warning_password = "輸入的密碼不合法!";
                        label_password.setText(warning_password);
                        System.out.println(warning_password);
                        textFieldPassword.setText("");

                    }   
                }else{
                    String warning_user = "輸入的使用者名稱不合法!";
                    label_user.setText(warning_user);
                    System.out.println(warning_user);
                    textFieldUserName.setText("");
                }                                                                           
            }
        });
        btnNewButton.setBounds(149, 248, 93, 23);
        contentPane.add(btnNewButton);

        label_user = new JLabel("");
        label_user.setBounds(285, 80, 150, 15);
        contentPane.add(label_user);

        label_password = new JLabel("");
        label_password.setBounds(289, 123, 150, 15);
        contentPane.add(label_password);

        label_passwordAgain = new JLabel("");
        label_passwordAgain.setBounds(289, 178, 150, 15);
        contentPane.add(label_passwordAgain);

    }
    private JLabel label_user;
    private JLabel label_password ;
    private JLabel label_passwordAgain;
}

登入

功能實現

資料庫中使用者和密碼的儲存:
這裡寫圖片描述

登入介面:
這裡寫圖片描述

登入程式碼

//SQLManager類
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

//採用單例設計模式
public class SQLManager {
    private Connection connection;
    private Statement statement;
    //獲得statement
    public Statement getStatement() {
        return statement;
    }
    //賦值statement
    public void setStatement(Statement statement) {
        this.statement = statement;
    }
    //獲得Connection
    public Connection getConnection() {
        return connection;
    }
    //賦值Connection
    public void setConnection(Connection connection) {
        this.connection = connection;
    }
    private static SQLManager manager;
    private SQLManager() {
        //連線資料庫的驅動
                String driver = "com.mysql.jdbc.Driver";
                //指向資料庫訪問地址
                String url = "jdbc:mysql://localhost:3306/clazz";
                //資料庫的使用者名稱
                String user = "root";
                //資料庫使用者密碼
                String password = "123456";

                try {
                    //載入驅動
                    Class.forName(driver);
                    //與資料庫建立連線
                    connection = DriverManager.getConnection(url,user, password);
                    if(!connection.isClosed()){
                        //建立資料庫操作類
                        statement = connection.createStatement();
                    }else{
                        System.out.println("請開啟資料庫!");
                    }

                } catch (ClassNotFoundException e) {            
                    e.printStackTrace();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
    }

    /**
     * 建立該類的物件
     * @return 返回SQLManager物件。
     */
    public static synchronized SQLManager newInstance(){
        if(manager==null){
            manager = new SQLManager();
        }
        return manager;
    }
}
//登入
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.awt.event.ActionEvent;

public class Login extends JFrame {

    private JPanel contentPane;
    private JTextField textUserName;
    private JTextField textPassword;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    Login frame = new Login();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
    /**
     * Create the frame.
     */
    public Login() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 451, 410);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);

        JLabel lblLogin = new JLabel("登入介面");
        lblLogin.setBounds(167, 57, 70, 31);
        contentPane.add(lblLogin);

        textUserName = new JTextField();
        textUserName.setBounds(153, 115, 137, 21);
        contentPane.add(textUserName);
        textUserName.setColumns(10);

        textPassword = new JTextField();
        textPassword.setBounds(153, 168, 137, 21);
        contentPane.add(textPassword);
        textPassword.setColumns(10);

        JButton btnNewButton = new JButton("登入");
        btnNewButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {

                String userName = textUserName.getText();
                String password = textPassword.getText();
                Connection conn = SQLManager.newInstance().getConnection();
                String sql = "select * from user where name= ? and password=? ";
                try {
                    PreparedStatement statement = conn.prepareStatement(sql);
                    statement.setString(1, userName);
                    statement.setString(2, password);
                    ResultSet set = statement.executeQuery();
                    set.last();//移動到最後一行。
                    int num = set.getRow();
                    if(num>0){
                        System.out.println(num);
                        System.out.println("使用者登入成功!");
                        textUserName.setText("");
                        textPassword.setText("");
                    }else{
                        System.out.println(num);
                        System.out.println("使用者登入失敗!");
                        textUserName.setText("");
                        textPassword.setText("");
                    }               
                } catch (SQLException e1) {
                    e1.printStackTrace();
                }       
            }
        });
        btnNewButton.setBounds(170, 246, 93, 23);
        contentPane.add(btnNewButton);

        JLabel lblUser = new JLabel("使用者名稱:");
        lblUser.setBounds(55, 118, 54, 15);
        contentPane.add(lblUser);

        JLabel lblPassword = new JLabel("密碼:");
        lblPassword.setBounds(55, 171, 54, 15);
        contentPane.add(lblPassword);
    }
}