DBLink
package zcdlxt_jdbc.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 zcdlxt_jdbc.tool.PropertiesTool;
/**
* 数据库管理工具类
*/
public class DBLink {
private Logger logger = Logger.getLogger(DBLink.class);
//获取数据裤链接
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语句是否能够查出数据
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;
}
//判断SQL语句是否能够查出数据
public boolean exist(String sql,Object...params) {//查询学号是否存在
Connection connection = null;
PreparedStatement prepareStatement = null;
ResultSet resultSet = null;
try {
connection = getConnection();//获取链接
prepareStatement = connection.prepareStatement(sql);
for (int i = 0; i < params.length; i++) {
prepareStatement.setObject(i + 1, params[i]);
}
resultSet = prepareStatement.executeQuery();
return resultSet.next();
} catch (Exception e) {
logger.debug(e.getMessage(), e);
} finally {
close(resultSet,prepareStatement ,connection);
}
return false;
}
//执行SQL语句查询数据
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);//因为rowMApper参数指向IRowMapper接口实现类对象,所以此处将调用接口实现类中所实现的中rowMApper方法。 多态
} catch (Exception e) {
logger.debug(e.getMessage(), e);
} finally {
close(resultSet,statement,connection);
}
}
//执行SQL语句查询数据
public void select(String sql,IRowMapper rowMapper,Object ...params) {
Connection connection = null;
PreparedStatement prepareStatement = null;
ResultSet resultSet = null;
try {
connection = getConnection();//获取链接
prepareStatement = connection.prepareStatement(sql);//含有?占位符的sql
for (int i = 0; i < params.length; i++) {
prepareStatement.setObject(i+1, params[i]);
}
resultSet = prepareStatement.executeQuery();
rowMapper.rowMapper(resultSet);
} catch (Exception e) {
logger.debug(e.getMessage(), e);
} finally {
close(resultSet,prepareStatement,connection);
}
}
//错误示范
/*public boolean update(String sql) {
try {
Class.forName("com.mysql.jdbc.Driver");//加载驱动
String url = "jdbc:mysql://127.0.0.1:3306/one";//指定连接哪一台计算机上的哪一个数据库实例
Connection connection = DriverManager.getConnection(url, "root", "545825");//获取数据库连接对象,一个对象表示一次数据库连接
Statement statement = connection.createStatement();//获取Statement对象
int result = statement.executeUpdate(sql);//执行sql语句,返回受影响的行数,仅限于数据insert、update、和delete
statement.close();//这两行代码不能写在这个地方。因为如果上面代码出现异常,则其下面代码无法执行,所以资源无法释放;比如sql语句语法错误,则statement和connection资源都无法释放
connection.close();
return result > 0;
} catch (Exception e) {
logger.debug(e.getMessage(), e);
}
return false;
}*/
//执行SQL语句修改(insert、update、delete)数据
public boolean update(String sql) {
Connection connection = null;
Statement statement = null;
try {
connection = getConnection();//获取数据库连接对象,一个对象表示一次数据库连接
statement = connection.createStatement();//获取Statement对象
int result = statement.executeUpdate(sql);//执行sql语句,返回受影响的行数,仅限于数据insert、update、和delete
// statement.close();//这两行代码不能写在这个地方。因为如果上面代码出现异常,则其下面代码无法执行,所以资源无法释放;比如sql语句语法错误,则statement和connection资源都无法释放
// connection.close();
return result > 0;
} catch (Exception e) {
logger.debug(e.getMessage(), e);
} finally {//即便有异常,也会执行
close(statement,connection);
}
return false;
}
//执行SQL语句修改(insert、update、delete)数据
public boolean update(String sql,Object ...params) {
Connection connection = null;
PreparedStatement prepareStatement = null;
try {
connection = getConnection();
prepareStatement = connection.prepareStatement(sql);//含有?占位符的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;
}
//释放资源
private void close(Statement statement,Connection connection) {
try {
if(statement != null) {//有可能由于异常导致statement没有赋值,比如url出错
statement.close();
}
} catch (SQLException e) {
logger.debug(e.getMessage(), e);
}
try {
if(connection != null) {
connection.close();
}
} catch (SQLException e) {
logger.debug(e.getMessage(), e);
}
}
//释放资源
private void close(ResultSet resultSet,Statement statement,Connection connection) {//重载
try {
if(resultSet != null) {
resultSet.close();
}
} catch (SQLException e) {
logger.debug(e.getMessage(), e);
}
close(statement,connection);
}
}
IRowMapper
package zcdlxt_jdbc.tool.db;
import java.sql.ResultSet;
public interface IRowMapper {
void rowMapper(ResultSet rs);
}
MD5Tool
package zcdlxt_jdbc.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 zcdlxt_jdbc.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) {
return properties.getProperty(key);
}
}
db.properties
db.username =
db.password =
db.url = jdbc:mysql://127.0.0.1:3306/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=D://32Wei_JDK_Yu_eclipse//eclipse_java_EE_32//Eclipse_GongZuoKongJian//zcdlxt_jdbc//log.log
log4j.appender.RollingFile.layout=org.apache.log4j.PatternLayout
log4j.appender.RollingFile.layout.ConversionPattern=%d [%t] %-5p %-40.40c %X{traceId}-%m%n
Main
package zcdlxt_jdbc.test;
import java.util.Scanner;
import java.util.UUID;
import zcdlxt_jdbc.tool.MD5Tool;
import zcdlxt_jdbc.tool.db.DBLink;
/*
* 问题:当DBA (数据库管理员)登陆数据库直接可以看到所有人的用户名和密码,有泄密的可能
*/
public class Main {
public static void main(String[] args) {
System.out.println("*********************************");
System.out.println("*\t\t\t\t*");
System.out.println("*\t欢迎使用注册登录系统\t*");
System.out.println("*\t\t\t\t*");
System.out.println("*********************************");
while (true) {
menu();
}
}
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:{
System.out.print("请输入用户名:");
String userName = scanner.next();
System.out.print("请输入密码:");
String password = scanner.next();
System.out.print("请确认密码:");
String rePassword = scanner.next();
String sql = "select id from user_info where user_name = ?";
if(new DBLink().exist(sql, userName)) {
System.out.println("此用户名已存在!注册失败");
return;
}
if(!password.equals(rePassword)) {
System.out.println("两次密码不一致!注册失败");
return;
}
String id = UUID.randomUUID().toString();
password = MD5Tool.encrypt(password);//密码加密
sql = "insert into user_info (id,user_name,password) values ('"+id+"',?,?)";
if(new DBLink().update(sql, userName, password)) {
System.out.println("注册成功!");
return;
}
System.out.println("注册失败!");
break;
}
case 2:{
System.out.print("请输入用户名:");
String userName = scanner.next();
System.out.print("请输入密码:");
String password = scanner.next();
password = MD5Tool.encrypt(password);
String sql = "select id from user_info where user_name = ? and password = ?";
if(new DBLink().exist(sql, userName, password)) {
System.out.println("登陆成功!");
return;
}
System.out.println("用户名或密码错误,登陆失败!");
break;
}
case 3:{
System.out.println("退出成功!");
System.exit(0);//终止程序
}
default:
System.out.println("I'm Sorry,there is not the "+option+" option,please try again.");
}
}
}