Java中使用DbUtils工具类对JDBC操作进行封装

案例:使用DbUtils数据库工具类,实现在控制台输入数字“1”或“2”,对数据库的查询和增加,具体功能如下图所示。

Java中使用DbUtils工具类对JDBC操作进行封装_第1张图片  

Java中使用DbUtils工具类对JDBC操作进行封装_第2张图片

项目分为三个文件,1、主界面JdbcDemo5.java文件      2、学生类Student.java文件,该类是具体的实现类   3、工具类DbUtils.java文件

1、主界面JdbcDemo.java中写了两个自定义方法,select()方法和add()方法,具体代码如下所示。

/**
 * 实现tb_student表的查询和添加
 */
public class JdbcDemo5
{

	public static void main(String[] args)
	{
		
		System.out.println("------欢迎进入xx操作系统------");
		System.out.println("请选择:  1查询  2添加  3更新  4删除");
		
		Scanner inScanner = new Scanner(System.in);
		int choice = inScanner.nextInt();
		
		switch (choice)
		{
			case 1:
				//查询功能
				ArrayList students = select();
				for (Student student:students)
				{
					System.out.println(student.toString());
				}
			break;
			
			case 2:
                                //添加功能
				add();
				break;
			
			case 3:
				
				break;
				
			case 4
                                //删除功能
				delete();
				break;

			default:
				System.out.println("输入有误..");
			break;
		}
		
	}
	/**
	 * 根据id删除学生信息
	 */
	private static void delete()
	{
		Scanner input = new Scanner(System.in);
		System.out.println("请输入要删除的员工编号:");
		int id = input.nextInt();
		int result = DbUtils.executeUpdate("delete from tb_student where id=?;",id);
		
		if (result>0)
		{
			System.out.println("删除成功...");
		}
	}

	/**
	 * 查询学生信息
	 */
	public static ArrayList select()
	{
		ArrayList students = new ArrayList();
		Connection connection = null; 
		PreparedStatement pstat = null;
		ResultSet resultSet = null;
		try
		{
			connection = DbUtils.getConnection();
			pstat = connection.prepareStatement("select * from tb_student;");
			resultSet = pstat.executeQuery();
			
			while(resultSet.next())
			{
				int id = resultSet.getInt("id");
				String name = resultSet.getString("name");
				String subject = resultSet.getString("subject");
				int score = resultSet.getInt("score");
				
				Student student = new Student(id, name, subject, score);
				students.add(student);
			}
		} catch (SQLException e)
		{
			e.printStackTrace();
		}
		finally {
			DbUtils.closeAll(resultSet, pstat, connection);
		}
		return students;
	}

	/**
	 * 添加学生信息
	 */
	public static void add()
	{
		Scanner input = new Scanner(System.in);
		System.out.println("请输入学生姓名:");
		String name = input.next();
		System.out.println("请输入学生科目:");
		String subject = input.next();
		System.out.println("请输入学生成绩:");
		int score = input.nextInt();
		
		//执行数据库操作
		Object[] objects = {name,subject,score};
		int result = DbUtils.executeUpdate("insert into tb_student(name,subject,score) values(?,?,?);",objects);
		
		if (result>0)
		{
			System.out.println("添加成功...");
		}
	}
}

2、学生类Student.java是一个具体的实现类,具体代码如下所示。

public class Student
{
	private int id;
	private String name;
	private String subject;
	private int score;
	
	public Student()
	{
		
	}

	public Student(int id, String name, String subject, int score)
	{
		super();
		this.id = id;
		this.name = name;
		this.subject = subject;
		this.score = score;
	}

	public int getId()
	{
		return id;
	}

	public String getName()
	{
		return name;
	}

	public String getSubject()
	{
		return subject;
	}

	public int getScore()
	{
		return score;
	}

	public void setId(int id)
	{
		this.id = id;
	}

	public void setName(String name)
	{
		this.name = name;
	}

	public void setSubject(String subject)
	{
		this.subject = subject;
	}

	public void setScore(int score)
	{
		this.score = score;
	}

	@Override
	public String toString()
	{
		return "Student [id=" + id + ", name=" + name + ", subject=" + subject + ", score=" + score + "]";
	}
}

 3.JDBC操作数据库的工具类。

/**
 *数据库驱动类
 *1、注册驱动(仅需要注册一次)
 *2、获取连接
 *3、关闭连接 
 *4、执行命令
 */
public class DbUtils
{
	//驱动名称com.mysql.jdbc.Driver
	private static String driver;
	//url 连接字符串jdbc:mysql://localhost:3306/db_test
	private static String url;
	//username:root
	private static String username;
	//password:123456
	private static String password;
	
	static
	{
                /*可以被替换掉,使用database.properties文件
		driver = "com.mysql.jdbc.Driver";
		url = "jdbc:mysql://localhost:3306/db_test";
		username = "root";
		password = "123456";
		*/
                /*下面是使用properties进行操作*/

                FileInputStream fis = null;
		try
		{
			Properties properties = new Properties();
			fis = new FileInputStream("src\\database.properties");
			properties.load(fis);
			driver = properties.getProperty("driver");
			url = properties.getProperty("url");
			username = properties.getProperty("username");
			password = properties.getProperty("password");
			
		} catch (IOException e)
		{
			e.printStackTrace();
		}finally {
			try
			{
				fis.close();
			} catch (IOException e)
			{
				e.printStackTrace();
			}
		}
                /*properties结束*/
                


		try
		{
			Class.forName(driver);
		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		
	}
	/**
	 * 获取连接
	 */
	public static Connection getConnection () 
	{
		try
		{
			return DriverManager.getConnection(url,username,password);
		} catch (SQLException e)
		{
			e.printStackTrace();
		}
		return null;
	}
	
	public static void closeAll(ResultSet resultSet,Statement statement, Connection connection)
	{
		if (resultSet!=null)
		{
			try
			{
				resultSet.close();
			} catch (SQLException e)
			{
				e.printStackTrace();
			}
		}
		if (statement!=null)
		{
			try
			{
				statement.close();
			} catch (SQLException e)
			{
				e.printStackTrace();
			}
		}
		if (connection!=null)
		{
			try
			{
				connection.close();
			} catch (SQLException e)
			{
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 执行命令 添加、删除和修改
	 * insert into emp(...) values(?,?,?)
	 * delete from emp where  id=?
	 */
	public static int executeUpdate(String sql,Object...objects)
	{
		//1、获取连接
		Connection connection = null;
		//2、创建命令对象
		PreparedStatement pstat = null;
		try
		{
			connection = getConnection();
			pstat = connection.prepareStatement(sql);
			for (int i = 0; i < objects.length; i++)
			{
				pstat.setObject(i+1, objects[i]); //向数据库中写入pstat.setInt(1,id);
			}
			//3、执行
			return pstat.executeUpdate(); //返回执行受到影响的行数
			
		} catch (Exception e)
		{
			// TODO: handle exception
			e.printStackTrace();
		}finally {
			closeAll(null, pstat, connection);
		}
		return 0 ;  //异常的话,则返回0
	}
}

4、使用database.properties配置文件进行操作

文件结构如下所示,代码见DbUtils类下注释部分。

Java中使用DbUtils工具类对JDBC操作进行封装_第3张图片

 

你可能感兴趣的:(Java学习)