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

Java-jdbc工具类jdbcUtil

时间:2017-06-16 16:40:27      阅读:379      评论:0      收藏:0      [点我收藏+]

标签:new   import   png   use   pre   java   runtime   time   sel   

在src文件夹下创建配置文件 db.properties

技术分享

 

db.properties

drivername=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mydb
user=root
password=root

  

JDBCUtil.java

package com.gordon.jdbcutil;

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

public class JDBCUtil {

	public static String DRIVERNAME = null;
	public static String URL = null;
	public static String USER = null;
	public static String PASSWORD = null;

	public static Connection conn = null;

	static {
		try {

			Properties props = new Properties();
			//Reader in = new FileReader("db.properties");
			InputStream in = JDBCUtil.class.getClassLoader().getResourceAsStream("db.properties");
			props.load(in);

			DRIVERNAME = props.getProperty("drivername");
			URL = props.getProperty("url");
			USER = props.getProperty("user");
			PASSWORD = props.getProperty("password");

		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public static Connection getConnection() throws Exception {
		if (conn != null) {
			return conn;
		}
		
		Class.forName(DRIVERNAME);
		conn = DriverManager.getConnection(URL, USER, PASSWORD);

		return conn;
	}

	public static void closeResource(Connection conn, PreparedStatement st) throws SQLException {
		st.close();
		conn.close();
	}

	public static void closeResource(Connection conn, ResultSet rs, PreparedStatement st) throws SQLException {
		st.close();
		rs.close();
		conn.close();
	}
}

  * 注意其中的获取配置文件的代码。

 

jdbc01.java测试文件

package com.gordon.jdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.gordon.jdbcutil.JDBCUtil;

public class jdbc01 {
	
	public static void main(String[] args) {
		selectFunction();
	}

	public static void selectFunction() {
		try {
			//1.获取连接
			Connection conn = JDBCUtil.getConnection();

			// 3.sql语句
			String sql = "SELECT * FROM user";

			// 3.获取SQL执行者
			PreparedStatement st = conn.prepareStatement(sql);

			// 4.设置参数

			// 5.执行sql语句
			ResultSet rs = st.executeQuery();

			// 6.处理数据
			while (rs.next()) {
				System.out.println(rs.getString("id") + ":" + rs.getString("name"));
			}

			// 7.释放资源
			JDBCUtil.closeResource(conn, rs, st);
			
		} catch (SQLException ex) {
			System.out.println(ex.getMessage());
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
	}
}

  

 

Java-jdbc工具类jdbcUtil

标签:new   import   png   use   pre   java   runtime   time   sel   

原文地址:http://www.cnblogs.com/hfultrastrong/p/7027652.html

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