Java之使用數據庫完成註冊、登陸操作以及MD5加密

項目框架結構

在這裏插入圖片描述

Properties

db.properties:

db.username=root
db.password=root
db.url=jdbc:mysql://192.168.77.14/test

log4j.properties:

# DEBUG\u8BBE\u7F6E\u8F93\u51FA\u65E5\u5FD7\u7EA7\u522B\uFF0C\u7531\u4E8E\u4E3ADEBUG\uFF0C\u6240\u4EE5ERROR\u3001WARN\u548CINFO \u7EA7\u522B\u65E5\u5FD7\u4FE1\u606F\u4E5F\u4F1A\u663E\u793A\u51FA\u6765
log4j.rootLogger=DEBUG,Console,RollingFile

#\u5C06\u65E5\u5FD7\u4FE1\u606F\u8F93\u51FA\u5230\u63A7\u5236\u53F0
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern= [%-5p]-[%d{yyyy-MM-dd HH:mm:ss}] -%l -%m%n
#\u5C06\u65E5\u5FD7\u4FE1\u606F\u8F93\u51FA\u5230\u64CD\u4F5C\u7CFB\u7EDFD\u76D8\u6839\u76EE\u5F55\u4E0B\u7684log.log\u6587\u4EF6\u4E2D
log4j.appender.RollingFile=org.apache.log4j.DailyRollingFileAppender
log4j.appender.RollingFile.File=E://log.log
log4j.appender.RollingFile.layout=org.apache.log4j.PatternLayout
log4j.appender.RollingFile.layout.ConversionPattern=%d [%t] %-5p %-40.40c %X{traceId}-%m%n

工具類

MD5Tool:

package com.jd.tool;

import java.math.BigInteger;
import java.security.MessageDigest;

public class MD5Tool {
	
	public static String encrypt(String password) {
		byte[] bytes = null;
		try {
			MessageDigest messageDigest = MessageDigest.getInstance("MD5");
			messageDigest.update(password.getBytes());//加密
			bytes = messageDigest.digest();//獲得加密結果
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		String result = new BigInteger(1, bytes).toString(16);// 將加密後的數據轉換爲16進制數字
		// 生成數字未滿32位,則前面補0
		for (int i = 0; i < 32 - result.length(); i++) {
			result = "0" + result;
		}
		return result;
	}
}

PropertiesTool:

package com.jd.tool;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class PropertiesTool {

  private static Properties properties = new Properties();
  
  static {
    InputStream inputStream = PropertiesTool.class.getClassLoader().getResourceAsStream("db.properties");//將db.properties變爲javaIO流對象
    try {
      properties.load(inputStream);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
  
  public static String getValue(String key) {
	  String value = properties.getProperty(key);
	  return value;
  }
}

dbLink:

package com.jd.tool.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.apache.log4j.Logger;

import com.jd.tool.PropertiesTool;

/**
 * 數據庫工具類
 * 
 * @author Administrator
 */
public class DBLink {
	
	private Logger logger = Logger.getLogger(DBLink.class);
	
	/**
	 * 獲取數據庫鏈接
	 * @return
	 */
	private Connection getConnection() {
		try {
			Class.forName("com.mysql.jdbc.Driver");//加載驅動
			String userName = PropertiesTool.getValue("db.username");
			String passWord = PropertiesTool.getValue("db.password");
			String url = PropertiesTool.getValue("db.url");
			return DriverManager.getConnection(url ,userName,passWord);
		} catch (Exception e) {
			logger.debug(e.getMessage(), e);
		}
		return null;
	}
	
	/**
	 * 判斷sql語句是否存在數據
	 * @param sql
	 * @return
	 */
	public boolean exist(String sql) {
		Connection connection = null;
		Statement statement = null;
		ResultSet resultSet = null;
		try {
			connection = getConnection();
			statement = connection.createStatement();
			resultSet = statement.executeQuery(sql);
			return resultSet.next();
			
		} catch (Exception e) {
			logger.debug(e.getMessage(), e);
		}finally {
			close(resultSet, statement, connection);
		}
		return false;
	}
	
	public boolean exist(String sql,Object ...params) {
		Connection connection = null;
		PreparedStatement preparedStatement = null;
		ResultSet resultSet = null;
		try {
			connection = getConnection();
			preparedStatement = connection.prepareStatement(sql);
			for (int i = 0; i < params.length; i++) {
				preparedStatement.setObject(i+1, params[i]);
			}
			resultSet = preparedStatement.executeQuery();
			return resultSet.next();
		} catch (Exception e) {
			logger.debug(e.getMessage(), e);
		}finally {
			close(resultSet, preparedStatement, connection);
		}
		return false;
	}
	
	/**
	 * 查詢數據
	 * @param sql
	 * @param rowMapper
	 */
	public void select(String sql, IRowMapper rowMapper) {//接口無法創建對象,所以rowMapper參數一定指向IRowMapper接口實現類對象
		Connection connection = null;
		Statement statement = null;
		ResultSet resultSet = null;
		try {
			connection = getConnection();
			statement = connection.createStatement();
			resultSet = statement.executeQuery(sql);
			rowMapper.rowMapper(resultSet);
			
		} catch (Exception e) {
			logger.debug(e.getMessage(), e);
		}finally {
			close(resultSet, statement, connection);
		}
		
	}
	
	/**
	 * 查詢數據
	 * @param sql
	 * @param rowMapper
	 */
	public void select(String sql, IRowMapper rowMapper,Object ...params) {//接口無法創建對象,所以rowMapper參數一定指向IRowMapper接口實現類對象
		Connection connection = null;
		PreparedStatement preparedStatement = null;
		ResultSet resultSet = null;
		try {
			connection = getConnection();
			preparedStatement = connection.prepareStatement(sql);//含有?佔位符的sql
			for (int i = 0; i < params.length; i++) {
				preparedStatement.setObject(i + 1, params[i]);//爲?賦值
			}
			resultSet = preparedStatement.executeQuery();//執行sql
			rowMapper.rowMapper(resultSet);
		} catch (Exception e) {
			logger.debug(e.getMessage(), e);
		}finally {
			close(resultSet, preparedStatement, connection);
		}
		
	}

	/**
	 * 修改(insert、update、delete)數據
	 * @param sql
	 * @return
	 */
	public boolean update(String sql) {
		Connection connection = null;
		Statement statement = null;
		try {
			connection = getConnection();
			System.out.println(connection);
			statement = connection.createStatement();//獲取statement對象
			int result = statement.executeUpdate(sql);//執行sql語句,返回受影響的行數
			return result>0;
		} catch (Exception e) {
			logger.debug(e.getMessage(), e);
		}finally {
			close(statement, connection);
		}
		return false;
	}
	
	/**
	 * 修改(insert、update、delete)數據
	 * @param sql
	 * @return
	 */
	public boolean update(String sql,Object ...params) {
		Connection connection = null;
		PreparedStatement prepareStatement = null;
		try {
			connection = getConnection();
			prepareStatement = connection.prepareStatement(sql);
			for (int i = 0; i < params.length; i++) {
				prepareStatement.setObject(i+1, params[i]);//爲?賦值
			}
			return prepareStatement.executeUpdate()>0;
		} catch (Exception e) {
			logger.debug(e.getMessage(), e);
		}finally {
			close(prepareStatement, connection);
		}
		return false;
	}
	
	/**
	 * 釋放資源
	 * @param statement
	 * @param connection
	 */
	private void close(Statement statement,Connection connection) {
		try {
			if(statement!=null) {
				statement.close();
			}				
		} catch (SQLException e) {
			logger.debug(e.getMessage(), e);
		}
		try {
			if(connection!=null) {
				connection.close();					
			}
		} catch (SQLException e) {
			logger.debug(e.getMessage(), e);
		}
	}
	
	/**
	 * 釋放資源
	 * @param statement
	 * @param connection
	 */
	private void close(ResultSet resultSet,Statement statement,Connection connection) {
		try {
			if(resultSet!=null) {
				resultSet.close();			
			}
		} catch (SQLException e) {
			logger.debug(e.getMessage(), e);
		}
		try {
			if(statement!=null) {
				statement.close();
			}				
		} catch (SQLException e) {
			logger.debug(e.getMessage(), e);
		}
		try {
			if(connection!=null) {
				connection.close();					
			}
		} catch (SQLException e) {
			logger.debug(e.getMessage(), e);;
		}
	}
}

IRowMapper:

package com.jd.tool.db;

import java.sql.ResultSet;

public interface IRowMapper {

	void rowMapper(ResultSet rs);
}

程序主體

Main:

package com.jd.test;

import java.util.Scanner;
import java.util.UUID;

import com.jd.tool.MD5Tool;
import com.jd.tool.db.DBLink;

public class Main {
	
	private static DBLink db = new DBLink();

	public static void main(String[] args) {
		System.out.println("*********************************");
		System.out.println("*\t\t\t\t*");
		System.out.println("*\t歡迎使用註冊登錄系統\t\t*");
		System.out.println("*\t\t\t\t*");
		System.out.println("*********************************");
		while (true) {
			menu();
		}
	}

	public static void menu() {
		System.out.println("1、註冊");//用戶名  密碼  確認密碼
		System.out.println("2、登錄");//用戶名和密碼
		System.out.println("3、退出");//System.exit(0);
		System.out.println("請輸入操作,以Enter鍵結束:");
		Scanner scanner = new Scanner(System.in);
		int option  = scanner.nextInt();
		switch (option) {
			case 1:{
				String name = null;
				String password = null;
				String rePassword = null;
				String id = null;
				String sql = null;
				System.out.println("請輸入用戶名:");
				name = scanner.next();
				sql = "select id from user_info where user_name=?";
				if(db.exist(sql,name)) {
					System.out.println("用戶名已經存在,註冊失敗");
					return;
				}
				System.out.println("請輸入密碼:");
				password = scanner.next();
				System.out.println("請輸入確認密碼");
				rePassword = scanner.next();
				if(!password.equals(rePassword)) {
					System.out.println("兩次輸入密碼不一致,註冊失敗");
					return;
				}
				id = UUID.randomUUID().toString();
				password = MD5Tool.encrypt(password);//進行加密後再儲存到數據庫中
				sql="insert into user_info (id,user_name,password) values ('"+id+"',?,?)";
				if(db.update(sql,name,password)) {
					System.out.println("註冊成功!");
					return;
				}
				System.out.println("註冊失敗!");
				break;
			}
			case 2:{
				String name = null;
				String password = null;
				String sql = null;
				System.out.println("請輸入用戶名:");
				name = scanner.next();
				System.out.println("請輸入密碼:");
				password = scanner.next();
				password = MD5Tool.encrypt(password);
				sql = "select id from user_info where user_name=? and password=?";
				if(db.exist(sql,name,password)) {
					System.out.println("登陸成功!");
					return;
				}
				System.out.println("登陸失敗!");
				break;				
			}
			case 3:{
				System.out.println("已退出系統");
				System.exit(0);
				break;
			}
			default:
				System.out.println("I'm Sorry,there is not the "+option+" option,please try again.");
		}
	}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章