码迷,mamicode.com
首页 > 数据库 > 详细

JDBC工具类

时间:2015-06-05 15:55:42      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:jdbc   工具类   连接数据库   

//在src下创建dbinfo.properties(/JDBDTest/src/dbinfo.properties)

className=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mydb2
user=root
password=root

///JDBDTest/src/com/huowolf/util/JdbcUtil.java

package com.huowolf.util;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class JdbcUtil {
	private static String className;
	private static String url;
	private static String user;
	private static String password;
	static{
		try {
			InputStream in = JdbcUtil.class.getClassLoader().getResourceAsStream("dbinfo.properties");
			Properties props = new Properties();
			props.load(in);
			className = props.getProperty("className");
			url = props.getProperty("url");
			user = props.getProperty("user");
			password = props.getProperty("password");
			Class.forName(className);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static Connection getConnection() throws Exception{
		return DriverManager.getConnection(url, user, password);	
	}
	
	public static void release(ResultSet rs,Statement stmt,Connection conn){
		try {
			if(rs!=null)
				rs.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}

		try {
			if(stmt!=null)
				stmt.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}

		try {
			if(conn!=null)
				conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}

	}


}
//测试类

package com.huowolf;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

import com.huowolf.util.JdbcUtil;

public class JdbcDemo {
	
	public static void main(String[] args) {
		Connection conn = null;
		Statement stmt = null;
		ResultSet rs = null;
		try {
			conn = JdbcUtil.getConnection();
			stmt = conn.createStatement();
			rs = stmt
					.executeQuery("select id,name,password,email,birthday from users");
			while (rs.next()) {
				System.out.println("------------------------");
				System.out.println(rs.getObject("id"));
				System.out.println(rs.getObject("name"));
				System.out.println(rs.getObject("password"));
				System.out.println(rs.getObject("email"));
				System.out.println(rs.getObject("birthday"));
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			JdbcUtil.release(rs, stmt, conn);
		}

	}

}



JDBC工具类

标签:jdbc   工具类   连接数据库   

原文地址:http://blog.csdn.net/huolang_vip/article/details/46375773

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!