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

Java-jdbc工具类DBUtils

时间:2017-06-17 14:24:28      阅读:200      评论:0      收藏:0      [点我收藏+]

标签:time   object   main   http   man   test   close   source   puts   

创建项目:

技术分享

 

 

导入相应jar包:

  看上图。

 

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();
	}
}

  

JavaBean类编写(User.java):

package com.gordon.bean;

public class User {

	private int id;
	private String name;

	public User() {

	}

	public int getId() {
		return id;
	}

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

	public String getName() {
		return name;
	}

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

  

JDBCUtils.java数据库工具类:

package com.gordon.jdbcutils;

import java.sql.Connection;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ArrayHandler;
import org.apache.commons.dbutils.handlers.ArrayListHandler;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ColumnListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import com.gordon.bean.User;
import com.gordon.jdbcutil.JDBCUtil;

public class JDBCUtils {
	public static void main(String[] args) {
		try {

			// insertFunction();
			// updateFunction();
			// deleteFunction();
			selectFunction();

		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
	}

	public static void selectFunction() throws Exception {
		/*
			ArrayHandler		将结果集中的第一条记录封装到一个Object[]数组中,数组中的每一个元素就是这条记录中的每一个字段的值
			ArrayListHandler	将结果集中的每一条记录都封装到一个Object[]数组中,将这些数组在封装到List集合中。
			BeanHandler		将结果集中第一条记录封装到一个指定的javaBean中。
			BeanListHandler		将结果集中每一条记录封装到指定的javaBean中,将这些javaBean在封装到List集合中
			ColumnListHandler	将结果集中指定的列的字段值,封装到一个List集合中
			ScalarHandler		它是用于单数据。例如select count(*) from 表操作。
		 */

		QueryRunner qr = new QueryRunner();
		Connection conn = JDBCUtil.getConnection();

		/** ArrayHandler */
		// 1
		String sql = "SELECT * FROM user LIMIT ?";
		Object[] params = { 1 };
		Object[] objArrayhandler = qr.query(conn, sql, new ArrayHandler(), params);
		System.out.println(objArrayhandler[0] + ":" + objArrayhandler[1]);

		// 2
		String sql = "SELECT * FROM user";
		Object[] params = {};
		List<Object[]> listobjArrayhandler = qr.query(conn, sql, new ArrayListHandler(), params);
		for (Object[] obj : listobjArrayhandler) {
			System.out.println(obj[0] + ":" + obj[1]);
		}

		
		
		/** BeanHandler */
		// 1
		String sql = "SELECT * FROM user LIMIT 1";
		Object[] params = {};
		User user = qr.query(conn, sql, new BeanHandler<User>(User.class), params);
		System.out.println(user.getId() + ":" + user.getName());

		// 2
		String sql = "SELECT * FROM user";
		Object[] params = {};
		List<User> userList = qr.query(conn, sql, new BeanListHandler<User>(User.class), params);
		for (User user : userList) {
			System.out.println(user.getId() + ":" + user.getName());
		}

		
		
		/** ColumnListHandler */
		// 1
		String sql = "SELECT max(id) FROM user";
		Object[] params = {};
		int maxid = qr.query(conn, sql, new ScalarHandler<Integer>(), params);
		System.out.println(maxid);

		// 2
		String sql = "SELECT name FROM user";
		Object[] params = {};
		List<String> userNameList = qr.query(conn, sql, new ColumnListHandler<String>(), params);
		for (String userName : userNameList) {
			System.out.println(userName);
		}
	}

	public static void deleteFunction() throws Exception {
		QueryRunner qr = new QueryRunner();
		String sql = "DELETE FROM user WHERE ID = ?";
		Object[] param = { 5 };
		Connection conn = JDBCUtil.getConnection();
		int res = qr.update(conn, sql, param);

		if (res > 0) {
			System.out.println("delete success.");
		} else if (res == 0) {
			System.out.println("deleted.");
		} else {
			System.out.println("delete faild.");
		}
	}

	public static void updateFunction() throws Exception {
		QueryRunner qr = new QueryRunner();
		String sql = "UPDATE user SET name = ? WHERE ID = ?";
		Object[] param = { "newname", 5 };
		Connection conn = JDBCUtil.getConnection();
		int res = qr.update(conn, sql, param);

		if (res > 0) {
			System.out.println("update success.");
		} else {
			System.out.println("update faild.");
		}
	}

	public static void insertFunction() throws Exception {

		/** 获取执行对象 */
		QueryRunner qr = new QueryRunner();

		/** sql */
		String sql = "INSERT INTO user (name) VALUES (?)";

		/** 参数 */
		Object[] param = { "testname" };

		/** 获取数据库连接 */
		Connection conn = JDBCUtil.getConnection();

		/** 执行sql */
		int res = qr.update(conn, sql, param);

		/** 处理结果 */
		if (res > 0) {
			System.out.println("insert success.");
		} else {
			System.out.println("insert faild.");
		}
	}
}

  

 

Java-jdbc工具类DBUtils

标签:time   object   main   http   man   test   close   source   puts   

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

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