0

0

Java获取数据库各种查询结果_MySQL

php中文网

php中文网

发布时间:2016-06-01 13:07:46

|

1054人浏览过

|

来源于php中文网

原创

在查询时候有时候要一条数据,有时候要的是一个结果集,然而有时候返回就是一个统计值,通过对ResultSet和ResultSetMetaData的变换得到各类所需的查询结果,因为没有利用连接池数据链接管理比较麻烦,所以谢了一个工具类,

package com.sky.connect;import java.lang.reflect.InvocationTargetException;import java.sql.ResultSet;import java.sql.SQLException;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import org.apache.commons.beanutils.BeanUtils;import com.mysql.jdbc.Connection;import com.mysql.jdbc.PreparedStatement;import com.mysql.jdbc.ResultSetMetaData;/** * DAO设计模式 *  * @author 潘琢文 *  */public class DAO {	/**	 * 更新数据库操作	 * 	 * @param sql	 * @param args	 */	public void update(String sql, Object... args) {		Connection connection = null;		PreparedStatement preparedStatement = null;		try {			connection = JDBCTools.getConnection();			preparedStatement = (PreparedStatement) connection					.prepareStatement(sql);			for (int i = 0; i < args.length; i++) {				preparedStatement.setObject(i + 1, args[i]);			}			preparedStatement.executeUpdate();		} catch (Exception e) {			e.printStackTrace();		} finally {			JDBCTools.release(preparedStatement, connection);		}	}	/**	 * 通用查询方法,返回一条记录	 * 	 * @param clazz	 * @param sql	 * @param args	 * @return	 */	public  T get(Class clazz, String sql, Object... args) {		T entity = null;		Connection connection = null;		PreparedStatement preparedStatement = null;		ResultSet result = null;		try {			connection = JDBCTools.getConnection();			preparedStatement = (PreparedStatement) connection					.prepareStatement(sql);			for (int i = 0; i < args.length; i++) {				preparedStatement.setObject(i + 1, args[i]);			}			result = preparedStatement.executeQuery();			Map map = new HashMap();			ResultSetMetaData rsmd = (ResultSetMetaData) result.getMetaData();			if (result.next()) {				for (int i = 0; i < rsmd.getColumnCount(); i++) {					String columnLabel = rsmd.getColumnLabel(i + 1);					Object value = result.getObject(i + 1);					map.put(columnLabel, value);				}			}			if (map.size() > 0) {				entity = clazz.newInstance();				for (Map.Entry entry : map.entrySet()) {					String filedName = entry.getKey();					Object filedObject = entry.getValue();					BeanUtils.setProperty(entity, filedName, filedObject);				}			}		} catch (Exception e) {			e.printStackTrace();		} finally {			JDBCTools.release(result, preparedStatement, connection);		}		return entity;	}	/**	 * 通用查询方法,返回一个结果集	 * 	 * @param clazz	 * @param sql	 * @param args	 * @return	 */	public  List getForList(Class clazz, String sql, Object... args) {		List list = new ArrayList();		Connection connection = null;		PreparedStatement preparedStatement = null;		ResultSet result = null;		try {			connection = JDBCTools.getConnection();			preparedStatement = (PreparedStatement) connection					.prepareStatement(sql);			for (int i = 0; i < args.length; i++) {				preparedStatement.setObject(i + 1, args[i]);			}			result = preparedStatement.executeQuery();			List> values = handleResultSetToMapList(result);			list = transfterMapListToBeanList(clazz, values);		} catch (Exception e) {			e.printStackTrace();		} finally {			JDBCTools.release(result, preparedStatement, connection);		}		return list;	}	/**	 * 	 * @param clazz	 * @param values	 * @return	 * @throws InstantiationException	 * @throws IllegalAccessException	 * @throws InvocationTargetException	 */	public  List transfterMapListToBeanList(Class clazz,			List> values) throws InstantiationException,			IllegalAccessException, InvocationTargetException {		List result = new ArrayList();		T bean = null;		if (values.size() > 0) {			for (Map m : values) {				bean = clazz.newInstance();				for (Map.Entry entry : m.entrySet()) {					String propertyName = entry.getKey();					Object value = entry.getValue();					BeanUtils.setProperty(bean, propertyName, value);				}				// 13. 把 Object 对象放入到 list 中.				result.add(bean);			}		}		return result;	}	/**	 * 	 * @param resultSet	 * @return	 * @throws SQLException	 */	public List> handleResultSetToMapList(			ResultSet resultSet) throws SQLException {		List> values = new ArrayList>();		List columnLabels = getColumnLabels(resultSet);		Map map = null;		while (resultSet.next()) {			map = new HashMap();			for (String columnLabel : columnLabels) {				Object value = resultSet.getObject(columnLabel);				map.put(columnLabel, value);			}			values.add(map);		}		return values;	}	/**	 * 	 * @param resultSet	 * @return	 * @throws SQLException	 */	private List getColumnLabels(ResultSet resultSet)			throws SQLException {		List labels = new ArrayList();		ResultSetMetaData rsmd = (ResultSetMetaData) resultSet.getMetaData();		for (int i = 0; i < rsmd.getColumnCount(); i++) {			labels.add(rsmd.getColumnLabel(i + 1));		}		return labels;	}	/**	 * 通用查询方法,返回一个值(可能是统计值)	 * 	 * @param sql	 * @param args	 * @return	 */	@SuppressWarnings("unchecked")	public  E getForValue(String sql, Object... args) {		Connection connection = null;		PreparedStatement preparedStatement = null;		ResultSet resultSet = null;		try {			connection = JDBCTools.getConnection();			preparedStatement = (PreparedStatement) connection					.prepareStatement(sql);			for (int i = 0; i < args.length; i++) {				preparedStatement.setObject(i + 1, args[i]);			}			resultSet = preparedStatement.executeQuery();			if (resultSet.next()) {				return (E) resultSet.getObject(1);			}		} catch (Exception e) {			e.printStackTrace();		} finally {			JDBCTools.release(resultSet, preparedStatement, connection);		}		return null;	}}

package com.sky.connect;import java.io.IOException;import java.io.InputStream;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.util.Properties;import com.mysql.jdbc.Connection;import com.mysql.jdbc.Driver;import com.mysql.jdbc.PreparedStatement;import com.mysql.jdbc.Statement;/** * JDBC操作的工具类 版本 1.0 *  * @author 潘琢文 *  */public class JDBCTools {	/**	 * 使用preparedStatement进行数据更新	 * 	 * @param sql	 * @param args	 */	public static void update(String sql, Object ... args) {		Connection connection = null;		PreparedStatement preparedStatement = null;		try {			connection = JDBCTools.getConnection();			preparedStatement = (PreparedStatement) connection					.prepareStatement(sql);			for (int i = 0; i < args.length; i++) {				preparedStatement.setObject(i + 1, args[i]);			}			preparedStatement.executeUpdate();		} catch (Exception e) {			e.printStackTrace();		} finally {			JDBCTools.release(preparedStatement, connection);		}	}	/**	 * 结果查询关闭	 * 	 * @param rs	 * @param statement	 * @param conn	 */	public static void release(ResultSet rs, Statement statement,			Connection conn) {		if (rs != null) {			try {				rs.close();			} catch (SQLException e) {				e.printStackTrace();			}		}		if (statement != null) {			try {				statement.close();			} catch (Exception e2) {				e2.printStackTrace();			}		}		if (conn != null) {			try {				conn.close();			} catch (Exception e2) {				e2.printStackTrace();			}		}	}	/**	 * 数据库更新方法	 * 	 * @param sql	 */	public void uodate(String sql) {		Connection connection = null;		Statement statement = null;		try {			connection = JDBCTools.getConnection();			statement = (Statement) connection.createStatement();			statement.executeUpdate(sql);		} catch (Exception e) {			e.printStackTrace();		} finally {			JDBCTools.release(statement, connection);		}	}	/**	 * 关闭数据库连接的方法	 * 	 * @param statement	 * @param conn	 */	public static void release(Statement statement, Connection conn) {		if (statement != null) {			try {				statement.close();			} catch (Exception e2) {				e2.printStackTrace();			}		}		if (conn != null) {			try {				conn.close();			} catch (Exception e2) {				e2.printStackTrace();			}		}	}	/**	 * 编写通用方法获取任意数据库链接,不用修改源程序	 * 	 * @return	 * @throws ClassNotFoundException	 * @throws IllegalAccessException	 * @throws InstantiationException	 * @throws SQLException	 * @throws IOException	 */	public static Connection getConnection() throws InstantiationException,			IllegalAccessException, ClassNotFoundException, SQLException,			IOException {		String driverClass = null;		String jdbcUrl = null;		String user = null;		String password = null;		// 读取properties文件		InputStream in = JDBCTools.class.getClassLoader().getResourceAsStream(				"jdbc.properties");		Properties properties = new Properties();		properties.load(in);		driverClass = properties.getProperty("driver");		jdbcUrl = properties.getProperty("url");		user = properties.getProperty("user");		password = properties.getProperty("password");		Class.forName(driverClass);		Connection connection = (Connection) DriverManager.getConnection(				jdbcUrl, user, password);		return connection;	}}

java速学教程(入门到精通)
java速学教程(入门到精通)

java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载

本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热门AI工具

更多
DeepSeek
DeepSeek

幻方量化公司旗下的开源大模型平台

豆包大模型
豆包大模型

字节跳动自主研发的一系列大型语言模型

通义千问
通义千问

阿里巴巴推出的全能AI助手

腾讯元宝
腾讯元宝

腾讯混元平台推出的AI助手

文心一言
文心一言

文心一言是百度开发的AI聊天机器人,通过对话可以生成各种形式的内容。

讯飞写作
讯飞写作

基于讯飞星火大模型的AI写作工具,可以快速生成新闻稿件、品宣文案、工作总结、心得体会等各种文文稿

即梦AI
即梦AI

一站式AI创作平台,免费AI图片和视频生成。

ChatGPT
ChatGPT

最最强大的AI聊天机器人程序,ChatGPT不单是聊天机器人,还能进行撰写邮件、视频脚本、文案、翻译、代码等任务。

相关专题

更多
2026赚钱平台入口大全
2026赚钱平台入口大全

2026年最新赚钱平台入口汇总,涵盖任务众包、内容创作、电商运营、技能变现等多类正规渠道,助你轻松开启副业增收之路。阅读专题下面的文章了解更多详细内容。

54

2026.01.31

高干文在线阅读网站大全
高干文在线阅读网站大全

汇集热门1v1高干文免费阅读资源,涵盖都市言情、京味大院、军旅高干等经典题材,情节紧凑、人物鲜明。阅读专题下面的文章了解更多详细内容。

40

2026.01.31

无需付费的漫画app大全
无需付费的漫画app大全

想找真正免费又无套路的漫画App?本合集精选多款永久免费、资源丰富、无广告干扰的优质漫画应用,涵盖国漫、日漫、韩漫及经典老番,满足各类阅读需求。阅读专题下面的文章了解更多详细内容。

50

2026.01.31

漫画免费在线观看地址大全
漫画免费在线观看地址大全

想找免费又资源丰富的漫画网站?本合集精选2025-2026年热门平台,涵盖国漫、日漫、韩漫等多类型作品,支持高清流畅阅读与离线缓存。阅读专题下面的文章了解更多详细内容。

12

2026.01.31

漫画防走失登陆入口大全
漫画防走失登陆入口大全

2026最新漫画防走失登录入口合集,汇总多个稳定可用网址,助你畅享高清无广告漫画阅读体验。阅读专题下面的文章了解更多详细内容。

13

2026.01.31

php多线程怎么实现
php多线程怎么实现

PHP本身不支持原生多线程,但可通过扩展如pthreads、Swoole或结合多进程、协程等方式实现并发处理。阅读专题下面的文章了解更多详细内容。

1

2026.01.31

php如何运行环境
php如何运行环境

本合集详细介绍PHP运行环境的搭建与配置方法,涵盖Windows、Linux及Mac系统下的安装步骤、常见问题及解决方案。阅读专题下面的文章了解更多详细内容。

0

2026.01.31

php环境变量如何设置
php环境变量如何设置

本合集详细讲解PHP环境变量的设置方法,涵盖Windows、Linux及常见服务器环境配置技巧,助你快速掌握环境变量的正确配置。阅读专题下面的文章了解更多详细内容。

0

2026.01.31

php图片如何上传
php图片如何上传

本合集涵盖PHP图片上传的核心方法、安全处理及常见问题解决方案,适合初学者与进阶开发者。阅读专题下面的文章了解更多详细内容。

2

2026.01.31

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号