jdbc工具类的封装

首先是工具类:

package com.fill.jweb_jdbc_new;

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;

/**
 * 
 * @author liufeihong
 *数据库操作工具类
 */
public class dbutils {
	public static String URL;
	public static  String USERNAME;
	public static  String PWD;
	public static  String DRIVER;
	private static ResourceBundle rb=ResourceBundle.getBundle("com.fill.jweb_jdbc_new.db-config");
	//防止工具类被实例化
	private dbutils(){}
	//保证只加载一次的东西
	static{
		//读配置文件
		URL=rb.getString("jdbc.url");
		USERNAME=rb.getString("jdbc.user");
		PWD=rb.getString("jdbc.pwd");
		DRIVER=rb.getString("jdbc.DRIVER");
		//加载驱动
		try {
			Class.forName(DRIVER);
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	//获取数据库连接
	public static Connection getConnection(){
		Connection conn=null;
		try {
			conn=(Connection) DriverManager.getConnection(URL, USERNAME, PWD);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("获取连接失败");
		}
		return conn;
	}
	public static void close(Statement sta,ResultSet re,Connection conn){

		try {
			if(sta!=null)
				sta.close();
			if(re!=null)
				re.close();
			if(conn!=null)	
				conn.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
}

属性文件:

db-config.properties

jdbc.url=jdbc:mysql://127.0.0.1:3308/test

jdbc.user=root

jdbc.pwd=root

jdbc.DRIVER=com.mysql.jdbc.Driver


下面开始测试:

package com.fill.jweb_jdbc_new;

import java.sql.ResultSet;
import java.sql.SQLException;

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

public class Test {

	public static void findAll(){
		//通过工具类获取数据库连接
		PreparedStatement ps=null;
		ResultSet rs=null;
		Connection conn=dbutils.getConnection();		
		String sql="select * from test where id>0";
		try {
			ps=(PreparedStatement) conn.prepareStatement(sql);
			rs=ps.executeQuery();
			while(rs.next()){
				System.out.println(rs.getString("name")+"<br>");
			}
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			dbutils.close(ps, rs, conn);
		}
	}
	public static void main(String[] args) {
		findAll();

	}
	
}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值