Intellij IDEA创建Java项目,连接SQL Server数据库项目,实现账号登录注册等基础功能。【入门学习】

07-11 1600阅读

目录

  • 一、创建SQL数据库文件
  • 二、下载和配置Maven文件
  • 三、编写Java项目源代码
  • 四、编写源代码文件
  • 五、结语

    今天为大家带来一个简单的JAVA项目,连接SQL Server数据库实现账号登录等功能,SQL Server2022,Intellij IDEA2023,java版本openjdk-21,maven版本3.9.6。

    我得说明一下,你直接运行这个源代码是没有用的!一步一步配置好环境来,再去运行。

    当然了,这个主要适合新人基础入门学习,话不多说,直接开始。

    一、创建SQL数据库文件

    1. 打开SQL数据库,记住服务器名称、登录名和密码这些信息:

    Intellij IDEA创建Java项目,连接SQL Server数据库项目,实现账号登录注册等基础功能。【入门学习】

    2. 创建一个“LoginRegister”数据库,在里面新建一张“账号登录”表。这个数据库和表的名字可以自定义,但是后面的代码里面相关信息也要对应修改,所以,熟悉后,再去修改,自己尝试一下。

    Intellij IDEA创建Java项目,连接SQL Server数据库项目,实现账号登录注册等基础功能。【入门学习】

    二、下载和配置Maven文件

    1. 可以去maven官网下载,自定义选择自己需要的版本,下面我以3.9.6版本进行演示。

    https://maven.apache.org/download.cgi

    https://archive.apache.org/dist/maven/maven-3/

    Intellij IDEA创建Java项目,连接SQL Server数据库项目,实现账号登录注册等基础功能。【入门学习】

    2. 下载后解压在指定位置,不要乱移动!在里面新建一个Repository仓库文件夹。

    Intellij IDEA创建Java项目,连接SQL Server数据库项目,实现账号登录注册等基础功能。【入门学习】

    3. 通过IDEA打开conf里面的settings.xml文件进行编辑。

    Intellij IDEA创建Java项目,连接SQL Server数据库项目,实现账号登录注册等基础功能。【入门学习】

    在这个位置添加下面这行代码。这个仓库位置一定是自己创建的仓库所在路径,看清楚!

      
      D:\Downloads\IDEA\apache-maven-3.9.6\Repository
    

    Intellij IDEA创建Java项目,连接SQL Server数据库项目,实现账号登录注册等基础功能。【入门学习】

    5. 然后往下滑,在这个位置添加下面这行代码,配置阿里云镜像文件:

        
        
          alimaven
          aliyun maven
          https://maven.aliyun.com/nexus/content/groups/public/
          central
        
    

    Intellij IDEA创建Java项目,连接SQL Server数据库项目,实现账号登录注册等基础功能。【入门学习】

    6. 然后在IDEA设置里面配置Maven文件和路径:

    Intellij IDEA创建Java项目,连接SQL Server数据库项目,实现账号登录注册等基础功能。【入门学习】

    三、编写Java项目源代码

    1. 新建一个java项目,如图所示:

    Intellij IDEA创建Java项目,连接SQL Server数据库项目,实现账号登录注册等基础功能。【入门学习】

    2. 如图所示进行创建文件,另外,不要忘记上面配置的maven设置。

    Intellij IDEA创建Java项目,连接SQL Server数据库项目,实现账号登录注册等基础功能。【入门学习】

    3. 下载SQL数据库驱动文件,在pom.xml文件里面添加下面这行代码:

        
            
                com.microsoft.sqlserver
                mssql-jdbc
                6.3.0.jre8-preview
            
        
    

    添加代码后,点击右上方的刷新进行下载。如图所示:

    Intellij IDEA创建Java项目,连接SQL Server数据库项目,实现账号登录注册等基础功能。【入门学习】

    4. 在jdbc.properties文件里面配置SQL数据库连接信息,添加下面这段代码:

    这里我没有直接在源代码里面写SQL连接信息,而是把它转到这个properties文件里面,一方面是方便调用,另一方面是方便修改。

    #导入SQL驱动
    jdbc.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver
    #SQL数据库地址,LoginRegister为数据库名称(不能为中文,会报错)
    jdbc.url=jdbc:sqlserver://localhost;databaseName=LoginRegister
    #SQL数据库登录名
    jdbc.username=sa
    #密码
    jdbc.password=123456
    

    如图所示:

    Intellij IDEA创建Java项目,连接SQL Server数据库项目,实现账号登录注册等基础功能。【入门学习】

    四、编写源代码文件

    1. 准备就绪后,开始写源代码。

    这个SQL连接信息封装在一个ConnectionString()方法里面,方便调用,演示一下如何使用。

    import java.io.IOException;
    import java.io.InputStream;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    import java.util.Properties;
    public class Main {
        public static void main(String[] args) throws SQLException {
    		//在主函数里面调用这个ConnectionString()方法
            Connection conn = ConnectionString();
            if (conn != null) {
            	//只要连接信息不为空
                System.out.println("数据库连接成功!");
            }
            else {
                System.out.println("数据库连接失败!");
            }
            conn.close();
        }
        
    	//返回数据库连接信息
        public static Connection ConnectionString() {
            Connection conn = null;
            try {
                // 读取jdbc.properties文件
                InputStream is = Main1.class.getClassLoader().getResourceAsStream("jdbc.properties");
                Properties props = new Properties();
                props.load(is);
                // 获取数据库连接
                Class.forName(props.getProperty("jdbc.driverClassName"));
                conn = DriverManager.getConnection(props.getProperty("jdbc.url"), props.getProperty("jdbc.username"), props.getProperty("jdbc.password"));
            }
            catch (IOException |
                   ClassNotFoundException |
                   SQLException e) {
                e.printStackTrace();
            }
            return conn;
        }
    }
    

    这里我还写了一个SHA-256加盐加密方法,主要是针对密码进行加密,然后存储在数据库里面。

    演示一下如何使用这个函数。

    import java.nio.charset.StandardCharsets;
    import java.security.MessageDigest;
    import java.security.NoSuchAlgorithmException;
    import java.util.Scanner;
    public class main2 {
        public static void main(String[] args) {
            Scanner scanner=new Scanner(System.in);
            System.out.println("请输入用户名:");
            String user=scanner.nextLine();
            System.out.println("请输入密码:");
            String pwd=scanner.nextLine();
            
            System.out.println("加密后的密码:"+EncryptWithSalt(user,pwd));
        }
        //SHA-256加盐加密
        public static String EncryptWithSalt(String username, String password) {
            String salt = username + password; // 盐值为用户名和密码拼接
            try {
                MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
                byte[] saltBytes = salt.getBytes(StandardCharsets.UTF_8);
                messageDigest.update(saltBytes);
                byte[] bytes = messageDigest.digest(password.getBytes(StandardCharsets.UTF_8));
                StringBuilder builder = new StringBuilder();
                for (byte aByte : bytes) {
                    builder.append(Integer.toString((aByte & 0xff) + 0x100, 16).substring(1));
                }
                String encryptedPassword = builder.toString();
                int length = encryptedPassword.length();
                //将加密后的密文长度缩短为原来的1/4,再输出返回
                if (length % 2 == 0) {
                    return encryptedPassword.substring(0, length / 4);
                }
                else {
                    return encryptedPassword.substring(0, (length - 1) / 4);
                }
            }
            catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            }
            return null;
        }
    }
    

    2. 以下是完整的源代码:

    import java.io.IOException;
    import java.io.InputStream;
    import java.nio.charset.StandardCharsets;
    import java.security.MessageDigest;
    import java.security.NoSuchAlgorithmException;
    import java.sql.*;
    import java.util.Properties;
    import java.util.Scanner;
    public class Main1 {
        public static Scanner scanner = new Scanner(System.in);
        //登录功能
        public static void Login() throws SQLException {
            System.out.println("\n***********************************************************************");
            System.out.println("**************************** 账号登录 *********************************");
            System.out.println("***********************************************************************");
            Connection conn = ConnectionString();
            if (conn != null) {
                //数据库连接成功
                System.out.print("请输入用户名:");
                String username = scanner.nextLine();
                System.out.print("请输入密码:");
                String password = scanner.nextLine();
                String sql = "SELECT * FROM 账号登录 WHERE username = ?";
                PreparedStatement stmt = conn.prepareStatement(sql);
                stmt.setString(1, username);
                ResultSet rs = stmt.executeQuery();
                if (rs.next()) {
                    // 账号存在,继续判断密码是否正确
                    String Password1 = rs.getString("password");
                    if (Password1.equals(EncryptWithSalt(username, password))) {
                        System.out.println("登录成功!");
                        conn.close();
                        Main2();
                    }
                    else {
                        System.out.println("密码错误!");
                        conn.close();
                        Login();
                    }
                }
                else {
                    // 账号不存在,跳转到注册功能
                    System.out.println("该账号不存在,请先注册账号!");
                    conn.close();
                    Main2();
                }
            }
            else {
                System.out.println("数据库连接失败!");
                conn.close();
                System.exit(0);
            }
        }
        //注册功能
        public static void Register() throws SQLException {
            System.out.println("\n***********************************************************************");
            System.out.println("**************************** 账号注册 *********************************");
            System.out.println("***********************************************************************");
            Connection conn = ConnectionString();
            if (conn != null) {
                System.out.print("请输入新账号:");
                String username = scanner.nextLine();
                System.out.print("请输入新密码:");
                String password1 = scanner.nextLine();
                System.out.print("请确认新密码:");
                String password2 = scanner.nextLine();
                if (!password1.equals(password2)) {
                    System.out.println("两次密码不相同,请重新输入!");
                    Register();
                }
                else {
                    String sql = "SELECT * FROM 账号登录 WHERE username = ?";
                    PreparedStatement stmt = conn.prepareStatement(sql);
                    stmt.setString(1, username);
                    ResultSet rs = stmt.executeQuery();
                    if (!rs.next()) {
                        //账户不存在,注册
                        IsRegister(username, password1);
                        conn.close();
                        Main2();
                    }
                    else {
                        System.out.println("该账号已经注册!");
                        conn.close();
                        Login();
                    }
                }
            }
            else {
                System.out.println("SQL数据库连接失败!");
                conn.close();
            }
        }
        //插入注册账号数据到数据库
        public static void IsRegister(String username, String password) {
            Connection conn = ConnectionString();
            try {
                // 插入账号和密码
                String sql = "INSERT INTO 账号登录 (username, password) VALUES (?, ?)";
                PreparedStatement stmt = conn.prepareStatement(sql);
                stmt.setString(1, username);
                stmt.setString(2, EncryptWithSalt(username, password));
                int rowsAffected = stmt.executeUpdate();
                if (rowsAffected > 0) {
                    System.out.println("账号注册成功!");
                    conn.close();
                }
                else {
                    System.out.println("账号注册失败!");
                    conn.close();
                }
            }
            catch (SQLException e) {
                e.printStackTrace();
            }
        }
        //修改账号密码
        public static void Change() throws SQLException {
            System.out.println("\n***********************************************************************");
            System.out.println("**************************** 修改密码 *********************************");
            System.out.println("***********************************************************************");
            Connection conn = ConnectionString();
            if (conn != null) {
                //数据库连接成功
                System.out.print("请输入账号:");
                String username = scanner.nextLine();
                System.out.print("请输入旧密码:");
                String oldpwd = scanner.nextLine();
                System.out.print("请输入新密码:");
                String newpwd = scanner.nextLine();
                String selectSql = "SELECT * FROM 账号登录 WHERE username = ? AND password = ?";
                PreparedStatement selectStmt = conn.prepareStatement(selectSql);
                selectStmt.setString(1, username);
                selectStmt.setString(2, EncryptWithSalt(username, oldpwd));
                ResultSet resultSet = selectStmt.executeQuery();
                if (resultSet.next()) {
                    //账号密码正确
                    if (!oldpwd.equals(newpwd)) {
                        IsChange(username, newpwd);
                        conn.close();
                        Main2();
                    }
                    else {
                        System.out.println("新旧密码不得相同!");
                        conn.close();
                        Change();
                    }
                }
                else {
                    System.out.println("账号或密码错误!");
                    conn.close();
                    Main2();
                }
            }
            else {
                System.out.println("数据库连接失败!");
                conn.close();
            }
        }
        //保存修改后的密码到数据库
        public static void IsChange(String username, String newpwd) {
            Connection conn = ConnectionString();
            try {
                // 新旧密码不同,进行密码修改
                String updateSql = "UPDATE 账号登录 SET password = ? WHERE username = ?";
                PreparedStatement updateStmt = conn.prepareStatement(updateSql);
                updateStmt.setString(1, EncryptWithSalt(username, newpwd));
                updateStmt.setString(2, username);
                int rowsAffected = updateStmt.executeUpdate();
                if (rowsAffected > 0) {
                    System.out.println("账号密码修改成功!");
                    conn.close();
                }
                else {
                    System.out.println("账号密码修改失败!");
                    conn.close();
                    Main2();
                }
            }
            catch (SQLException e) {
                e.printStackTrace();
            }
        }
        //账号注销
        public static void Delete() throws SQLException {
            System.out.println("\n***********************************************************************");
            System.out.println("**************************** 账号注销 *********************************");
            System.out.println("***********************************************************************");
            Connection conn = ConnectionString();
            if (conn != null) {
                System.out.print("请输入账号:");
                String username = scanner.nextLine();
                System.out.print("请输入密码:");
                String password = scanner.nextLine();
                String selectSql = "SELECT * FROM 账号登录 WHERE username = ? AND password = ?";
                PreparedStatement selectStmt = conn.prepareStatement(selectSql);
                selectStmt.setString(1, username);
                selectStmt.setString(2, EncryptWithSalt(username, password));
                ResultSet resultSet = selectStmt.executeQuery();
                if (resultSet.next()) {
                    //账号密码正确
                    IsDelete(username);
                }
                else {
                    System.out.println("账号或密码错误!");
                }
            }
            else {
                System.out.println("数据库连接失败!");
            }
            conn.close();
            Main2();
        }
        //从数据库删除注销账号数据
        public static void IsDelete(String username) {
            Connection conn = ConnectionString();
            try {
                String deleteSql = "DELETE FROM 账号登录 WHERE username = ?";
                PreparedStatement deleteStmt = conn.prepareStatement(deleteSql);
                deleteStmt.setString(1, username);
                int rowsAffected = deleteStmt.executeUpdate();
                if (rowsAffected > 0) {
                    System.out.println("账号注销成功!");
                }
                else {
                    System.out.println("账号注销失败!");
                }
            }
            catch (SQLException e) {
                e.printStackTrace();
            }
        }
        public static void Main2() throws SQLException {
            System.out.println("\n***********************************************************************");
            System.out.println(" 1、账号登录;2、账号注册;3、修改密码;4、注销账号;0、退出程序. ");
            System.out.println("***********************************************************************");
            System.out.print("请输入选择:");
            String num = scanner.nextLine().trim();
            while (true) {
                switch (num) {
                    case "1" -> Login();
                    case "2" -> Register();
                    case "3" -> Change();
                    case "4" -> Delete();
                    case "0" -> {
                        System.out.println("程序已退出!\n");
                        System.exit(0);
                    }
                    default -> {
                        System.out.print("请重新输入选择:");
                        num = scanner.nextLine().trim();
                    }
                }
            }
        }
        public static void main(String[] args) throws SQLException {
            Main2();
        }
        //数据库连接信息
        public static Connection ConnectionString() {
            Connection conn = null;
            try {
                // 读取jdbc.properties文件
                InputStream is = Main1.class.getClassLoader().getResourceAsStream("jdbc.properties");
                Properties props = new Properties();
                props.load(is);
                // 获取数据库连接
                Class.forName(props.getProperty("jdbc.driverClassName"));
                conn = DriverManager.getConnection(props.getProperty("jdbc.url"), props.getProperty("jdbc.username"), props.getProperty("jdbc.password"));
            }
            catch (IOException |
                   ClassNotFoundException |
                   SQLException e) {
                e.printStackTrace();
            }
            return conn;
        }
        //SHA-256加盐加密
        public static String EncryptWithSalt(String username, String password) {
            String salt = username + password; // 盐值为用户名和密码拼接
            try {
                MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
                byte[] saltBytes = salt.getBytes(StandardCharsets.UTF_8);
                messageDigest.update(saltBytes);
                byte[] bytes = messageDigest.digest(password.getBytes(StandardCharsets.UTF_8));
                StringBuilder builder = new StringBuilder();
                for (byte aByte : bytes) {
                    builder.append(Integer.toString((aByte & 0xff) + 0x100, 16).substring(1));
                }
                String encryptedPassword = builder.toString();
                int length = encryptedPassword.length();
                if (length % 2 == 0) {
                    return encryptedPassword.substring(0, length / 4);
                }
                else {
                    return encryptedPassword.substring(0, (length - 1) / 4);
                }
            }
            catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            }
            return null;
        }
    }
    

    五、结语

    说实话,距离上一次发布文章,隔了将近1年的时间,这段时间一直没有动力,一直没有去锻炼自己的编程能力。接下来的时间还得继续努力,一起加油吧!

VPS购买请点击我

文章版权声明:除非注明,否则均为主机测评原创文章,转载或复制请以超链接形式并注明出处。

目录[+]