課後練習-登入-2024/9/29

XYu1230發表於2024-09-29

該登入介面是用JOptionPane彈窗接收使用者名稱和密碼,之後在資料庫中搜尋是否存在,最後顯示登入成功與否實現

loginTest.java

package JDBC_Test;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import javax.swing.*;
import java.io.FileInputStream;
import java.sql.*;
import java.util.Properties;

public class loginTest {
    public static void main(String[] args) throws Exception{
        String username,password;

        username = JOptionPane.showInputDialog( "輸入使用者名稱" );
        password = JOptionPane.showInputDialog( "輸入密碼" );

        if(isExist(username, password)){
            JOptionPane.showMessageDialog(
                    null, "登入成功!", ">_<",
                    JOptionPane.PLAIN_MESSAGE );
        }
        else {
            JOptionPane.showMessageDialog(
                    null, "登入失敗!", "<_>",
                    JOptionPane.PLAIN_MESSAGE );
        }

    }

    public static boolean isExist(String username,String password) throws Exception{

        //普通連線
        /*String url = "jdbc:mysql://localhost:3306/lxy?useSSL=false";
        String user = "root";
        String pw = "123456";*/

        //資料庫連線池獲取資料庫連線
        //載入配置檔案
        Properties prop = new Properties();
        prop.load(new FileInputStream("jdbc-demo/src/druid.properties"));
        DataSource dataSource = DruidDataSourceFactory.createDataSource(prop);

        Connection conn = dataSource.getConnection();

        String sql = "select * from user;";
        PreparedStatement pstmt = conn.prepareStatement(sql);
        ResultSet rs = pstmt.executeQuery();
        while(rs.next()){
            String u = rs.getString("username");
            String p = rs.getString("password");
            if(u.equalsIgnoreCase(username) && p.equalsIgnoreCase(password)){
                conn.close();
                pstmt.close();
                return true;
            }
        }
        conn.close();
        pstmt.close();
        return false;
    }
}

druid.properties配置檔案

driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql:///lxy?useSSL=false&useServerPrepStmts=true
username=root
password=123456

# 初始化連線數量
initialSize=5
# 最大連線數
maxActive=10
# 最大等待時間
maxWait=3000

資料庫user表為

相關文章