天天看点

Mysql_封装jdbc工具类

封装工具栏就是一个抽象的过程,我们可以吧现在代码中非常公用的代码抽取出来,形成一个工具栏。

第一步:抽象公共的代码到工具栏

第二步:为提高可以连接不同数据库的能力,连接数据库的URL、用户名、密码等信息编写在一个属性(jdbc.properties)中。

使用配置文件对 属性值进行封装

db.config-properties

jdbc.url  = jdbc:mysql://localhost:3306/test

jdbc.username=root

jdbc.password=root

jdbc.driver=com.mysql.jdbc.Driver

<pre name="code" class="java"><pre name="code" class="java">package com.test;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ResourceBundle;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;

/*
 * 数据库操作工具类
 * 
 */
public class DBUtils {
	public static String URL ;
	public static String USERNAME ;
	public static String PASSWORD ;
	public static String DRIVER ;
	
	private static ResourceBundle rb=ResourceBundle.getBundle("com.test.db-config");
	
	private DBUtils(){}
	//使用静态块加载驱动程序
	static{
			URL=rb.getString("jdbc.url");
			USERNAME=rb.getString("jdbc.username");
			PASSWORD=rb.getString("jdbc.password");
			DRIVER=rb.getString("jdbc.driver");
		try {
			Class.forName(DRIVER);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	//定义一个获取数据可连接的方法
	public static java.sql.Connection getConnection(){
		java.sql.Connection conn=null;
		try {
			conn=DriverManager.getConnection(URL,USERNAME,PASSWORD);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("获取连接失败");
		}
		return conn;
	}
	/*
	 * 关闭数据库连接
	 */
	public static void close(ResultSet rs,Statement stat,Connection conn){
			try {
				if(rs!=null)rs.close();
				if(stat!=null)stat.close();
				if(conn!=null)conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		
	}
	
}
           
<pre name="code" class="java">package com.test;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;


public class Test {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		findAll();
	}

		public static void findAll(){
			//通过工具类获取数据库连接
			com.mysql.jdbc.Connection conn=(Connection) DBUtils.getConnection();
			com.mysql.jdbc.PreparedStatement ps=null;
			ResultSet rs=null;
			String sql="select id,name,age,description from person1";
			try {
				ps=(PreparedStatement) conn.prepareStatement(sql);
				rs=ps.executeQuery();
				while(rs.next()){
					Person p=new Person();
					p.setId(rs.getInt(1));
					p.setName(rs.getString(2));
					p.setAge(rs.getInt(3));
					p.setDes(rs.getString(4));
					System.out.println(p);
					
				}
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}finally{
				DBUtils.close(rs, ps, conn);
			}
		}
		
		
}
           

继续阅读