JDBC工具类

3 篇文章 0 订阅

本文主要是将JDBC最基础的增删改查的工具类的代码详细的罗列出来:

一、我们先来看一看项目结构:

项目结构

二、配置JDBC工具类

1.我们先处理异常

我们知道几乎不可能一次性就写出完美的代码,都是要经过很多次的调试才行,那在调试过程中就难免会出现各种各样的异常情况,而控制台(console)的容量相对有限,有时不可能将异常情况全部打印出来,这样就不利于接下来的调试和改进代码,所以为了将全部的异常情况都显示出来我们就需要通过log4j.properties来输入全部的异常,我们需要先下一个log4j-1.2.15.jar的jar包,然后再创建一个文件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://log.log
log4j.appender.RollingFile.layout=org.apache.log4j.PatternLayout
log4j.appender.RollingFile.layout.ConversionPattern=%d [%t] %-5p %-40.40c %X{traceId}-%m%n

不要被吓到了,这个无需深入了解,网上也有类似的配置,我们在这里简单介绍一下:

我们从中可以看到Loggers、Appenders、Layouts,其实这就是Log4j的三个主要的组件:

  • Loggers(记录器):日志类别和级别(这里就是指异常的类别和级别)
    Loggers组件在系统中被分为五个级别:DEBUG < INFO < WARN < ERROR < FATAL(按日志信息的重要程度来排序);
    log4j有一个规则就是 只输出级别不低于设定级别的日志,这里设定为DEBUG,所以五个级别的异常都可以被输出。
  • Appenders(输出源):日志要输出的地方(我们可看到后面有个console,意思就是把异常输出到控制台)
    还可以根据天数或者文件大小产生新的文件,可以以流的形式发送到其他地方等等
    我们看到这里用的类是org.apache.log4j.DailyRollingFileAppender(意思就是每天产生一个新的文件)
  • Layouts(布局):日志以何种形式输出
    这里用的是org.apache.log4j.PatternLayout(意思就是可以灵活地指定布局模式)

那配置完jd.properties文件后,该怎么使用它呢?我们通过一个例子来了解:

import org.apache.log4j.Logger;

public class Test {

	//通过logger来使用
	private static Logger logger = Logger.getLogger(Test.class);
	
	//测试:
	public static void main(String[] args) {
		/*try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (Exception e) {
			e.printStackTrace();//此时是将错误打印到控制台上
		}*/
		
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (Exception e) {
			logger.debug(e.getMessage(),e);//getMessage()用来获取异常信息
		}
	}
}

2.连接MySQL数据库

我们平时连接MySQL数据库是这样连的:
先添加一个jar包:mysql-connector-java-5.1.44-bin.jar(可以在网上找到),然后

	Class.forName("com.mysql.jdbc.Driver");//加载驱动
	String url= "jdbc:mysql://127.0.0.1:3306/test";
	Stirng userName = "root";
	String password = "root";
	Connection connection = DriverManger.getConnection(url, userName, password);//获取数据库的连接对象

2.1创建db.properties文件

但这是固定地连接在一台计算机上的某个数据库实例,当我们需要连接另一台计算机或者其他实例又或者数据库发生改变时,Java的.class文件无法修改,所以就需要在Java的代码中一个一个修改,一个一个重新编译,不仅费时还费事。为了解决这个问题,我们就需要配置db.properties(MySQL数据库连接文件),将连接数据库所需的信息放进该文件,后期数据库改变时只需更改该文件即可(省时又省事):

  • 先在src根目录里创建一个文件(db.properties),内容为:
# 加载驱动
db.driver = com.mysql.jdbc.Driver
# 加载数据库
db.url=jdbc:mysql://127.0.0.1:3306/test
# 用户名
db.usernName=root
# 密码
db.password=root

2.2创建PropertiesTool类

  • 这时的db.properties文件还只是普通文件,还没有跟Java代码联系起来,那如何联系呢?这就需要一个中介来做媒,而充当中介的就是PropertiesTool.class(Properties工具类),其实Properties的父类就是HashTable,而HashTable的父类就是Map,所以Properties就是一个Map文件,可以往里面传值{key(键),value(值)},也就是说通过PropertiesTool可以将db.properties文件中的数据库配置信息转换成Properties中的key和value,这样就可以调用了:
package jdbc.tool;

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

public class PropertiesTool {

	private static Properties properties = new Properties();
  
	/**
	 * 联系db.properties文件和properties
	 * 
	 * 静态代码块先于main方法执行
	 */
	static {
		//将db.properties变为javaIO流对传入到inputStream中
		InputStream inputStream = PropertiesTool.class.getClassLoader().getResourceAsStream("db.properties");
		//此时db.properties文件中的数据就保存到了inputStream中
		try {
			properties.load(inputStream);//将inputStream中的key和value放到load方法中进行解析再存到properties中
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
  
	/**
	 * 我们创建一个getVaule方法来便于调用文件(此时也就是properties)中的数据
	 */
	public static String getValue(String key) {
		return properties.getProperty(key);//返回properties中的key值
	  
	}
  
	/**
	 * 我们来测试一下:
	 */
	public static void main(String [] ages) {
		String driver = getValue("db.driver");
		String url = getValue("db.url");
		String userName = getValue("db.userName");
		String password = getValue("db.password");
		System.out.println(driver);
		System.out.println(userName);
		System.out.println(password);
		System.out.println(url);
	}
}

结果正如我们所预料的那样:

com.mysql.jdbc.Driver
jdbc:mysql://127.0.0.1:3306/test
root
root

这时我们就可以通过PropertiesTool来连接数据库了:

	String driver = PropertiesTool.getValue("db.driver");
	String   url    = PropertiesTool.getValue("db.url");
	String userName = PropertiesTool.getValue("db.userName");
	String password = PropertiesTool.getValue("db.password");
	Class.forName(driver);
	Connection connection = DriverManger.getConnection(url, userName, password);//获取数据库的连接对象

这样的话,当IP地址或数据库改变时只需变动db.Properties文件即可,省时省事!

二、实现JDBC工具类(DBLink类)

package 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 jdbc.tool.PropertiesTool;

/**
 * 数据库管理(增删改查)
 * 
 * @author ZhaoZhengyi
 */

public class DBLink {
	
	private Logger logger = Logger.getLogger(DBLink.class);
	
	/**
	 * 获取数据库连接
	 *
	 * @author ZhaoZhengyi
	 */
	public  Connection getConnection() {
		try {
			String driver = PropertiesTool.getValue("db.driver");
			String   url    = PropertiesTool.getValue("db.url");
			String userName = PropertiesTool.getValue("db.userName");
			String password = PropertiesTool.getValue("db.password");
			Class.forName(driver);
			return DriverManager.getConnection(url, userName, password);
		} catch (Exception e) {
			logger.debug(e.getMessage(), e);
		}
		return null;
	}
	
	/**
	 * 判断某条数据是否存在
	 *
	 * @author ZhaoZhengyi
	 */
	public boolean exist(String sql,Object ...params) {
		//初始化变量为null
		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();//executeQuery用于查询用户的数据,并将其存入ResultSet类型的resultset变量中去
		
			return resultset.next();//若有则返回该用户数据
					
		} catch (Exception e) {
			logger.debug(e.getMessage(), e);
		} finally {//即便有异常也会执行代码
			close(resultset,prepareStatement,connection);//释放资源
		}
		return false;//若没有则返回false
	}
	
	/**
	 * 用于添加、删除、修改用户信息
	 *
	 * @author ZhaoZhengyi
	 */
	public boolean update(String sql, Object ...params) {
		Connection connection = null;
		PreparedStatement  prepareStatement = null;
		try {
			connection = getConnection();
			prepareStatement = connection.prepareStatement(sql);//含有?的sql语句 赋值给prepareStatement
			for(int i = 0; i < params.length; i++) {
				prepareStatement.setObject(i+1, params[i]);//用参数替换掉?
			}
			
			int affect = prepareStatement.executeUpdate();//执行sql语句,并返回影响的行数
			return affect>0;
		} catch (Exception e) {
			logger.debug(e.getMessage(), e);
		} finally {
			close(prepareStatement,connection);
		}
		return false;
	}
	
	/**
	 * 查询用户数据
	 *
	 * @author ZhaoZhengyi
	 */
	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);
			for (int i = 0; i < params.length; i++) {
				prepareStatement.setObject(i+1, params[i]);
			}
			resultset = prepareStatement.executeQuery();//执行SQL语句,此时用户数据都在resultset里面
			rowMapper.rowMapper(resultset);//因为rowMapper参数指向IRowMapper接口实现类对象,所以此处将调用接口实现类中所实现的rowMapper方法  多态
			
		} catch (Exception e) {
			logger.debug(e.getMessage(), e);
		} finally {
			close(resultset,prepareStatement,connection);//释放资源
		}
		
	}

	/**
	 * 释放资源
	 *
	 * @author ZhaoZhengyi
	 */
	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);
		}
	}
	
	/**
	 * 与上一方法是重载
	 *
	 * @author ZhaoZhengyi
	 */
	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);
	}
	
}

三、调用JDBC工具类(DBLink类)

首先创建一个接口IRowMapper:

package jdbc.tool.db;

import java.sql.ResultSet;

public interface IRowMapper {

	/**
	 * 定义一个抽象方法(参数类型为ResultSet)
	 *
	 * @author ZhaoZhengyi
	 */
	void rowMapper (ResultSet rs);
}

再创建一个Main方法去调用JDBC工具类:

package jdbc.main;

import java.sql.SQLException;
import java.util.Scanner;

import jdbc.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*");
		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.out.println("4、查询学生信息");//name
		System.out.println("请输入操作,以Enter键结束:");
		Scanner scanner = new Scanner(System.in);
		int option  = scanner.nextInt();
		switch (option) {
			case 1:{
				System.out.println("请输入学号:");
				String id = scanner.next();
				String sql = "select id from user_info where id = '"+id+"'";
				if(db.exist(sql)) {
					System.out.println("学号已存在,无法添加!");
					return;
				}
				
				System.out.println("请输入姓名:");
				String name = scanner.next();
				System.out.println("请输入手机号:");
				String mobile = scanner.next();
				System.out.println("请输入家庭地址:");
				String address = scanner.next();
				sql = "insert into user_info(id,name,mobile,address) values('"+id+"','"+name+"','"+mobile+"','"+address+"') ";
				if(db.update(sql)) {
					System.out.println("添加成功!");
					return;
				}
				System.out.println("系统异常,添加失败!");
			break;
			}
			case 2:{
				System.out.println("请输入要删除学生的学号:");
				String id = scanner.next();
				String sql = "select name from user_info where id ='"+id+"'";
				if(db.exist(sql)) {
					System.out.println("学号存在,可以删除,");
					sql = "delete from user_info where id ='"+id+"'";
					db.update(sql);
					System.out.println("删除成功!");
					return;
				}
				System.out.println("学号不存在,无法删除!");
				break;
			}
			case 3:{
				System.out.println("请输入要修改学生的学号:");
				String id = scanner.next();
				String sql = "select name from user_info where id ='"+id+"'";
				if(!db.exist(sql)) {
					System.out.println("学号不存在,无法修改,");
					return;
				}
				
				System.out.println("请输入新姓名:");
				String name = scanner.next();
				System.out.println("请输入新手机号:");
				String mobile = scanner.next();
				System.out.println("请输入新家庭地址:");
				String address = scanner.next();
				sql = "update user_info set name='"+name+"',mobile='"+mobile+"',address='"+address+"' where id='"+id+"'";
				if(db.update(sql)) {
					System.out.println("修改成功!");
					return;
				}
				System.out.println("系统异常,修改失败!");
				break;
			}
			case 4:{
				System.out.println("请输入要查询学生的学号:");
				String id = scanner.next();
				String sql = "select name from user_info where id ='"+id+"'";
				if(!db.exist(sql)) {
					System.out.println("学号不存在,查询无果!");
					return;
				}
				sql = "select id,name,mobile,address from user_info where id ='"+id+"'";
				//有名内部类
				class RowMapper implements IRowMapper{

					@Override
					public void rowMapper(ResultSet rs) {
						try {
							if(rs.next()) {
								String id1 = rs.getString("id");
								String name = rs.getString("name");
								String mobile = rs.getString("mobile");
								String address = rs.getString("address");
								System.out.println("学号:"+id1+",姓名:"+name+",手机号:"+mobile+",家庭地址:"+address);
							}
						} catch (SQLException e) {
							e.printStackTrace();
						}
					}
					
				}
				RowMapper rowMapper = new RowMapper();
				db.select(sql, rowMapper);
		
				break;
			}
			default:
				System.out.println("I'm Sorry,there is not the "+option+" option,please try again.");
		}
	}
}

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

不动声色的小蜗牛

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值