---
title: "一个通用查询（原创）"
author: "breezedancer"
date: "2007-05-22T12:59:23Z"
tags: []
categories: ["企业架构"]
slug: "untitled"
draft: false
lastmod: "2007-05-22T12:59:23Z"
id: 81801
url: "https://breezedancer.iteye.com/blog/81801"
---

java 代码

01. package com.abc.www;
02. import java.lang.reflect.InvocationTargetException;
03. import java.lang.reflect.Method;
04. import java.sql.\*;
05. import java.util.ArrayList;
06. public class NewTestReflect {
07. public static void main(String\[] args) throws Exception {
08. NewTestReflect newtestreflect=new NewTestReflect();
09. newtestreflect.select("select * from test", "com.tangshun.www.Person");
10. }
11. private static String getSetMethodName(String columnName) {
12. return "set" + columnName.substring(0, 1).toUpperCase()
13. + columnName.toLowerCase().substring(1);
14. }
15. /\**
16. * 需要提供sql语句，以及操作数据库表对应的类名字（包括包名）
17. * 如：select * from test;则类名字应该是   包.Test
18. * Test.java是一个简单的pojo，对数据库里面的字段只有相应的set get方法
19. * 如果有必要，可以增加其他相关的构造方法等
20. * @param sql
21. * @param className
22. * @return ArrayList
23. \*/
24. public ArrayList select(String sql, String className) {
25. Connection connection = null;
26. PreparedStatement stmt = null;
27. ResultSet rs = null;
28. ArrayList paraList = new ArrayList();
29. try {
30. Class.forName("com.mysql.jdbc.Driver");
31. connection = DriverManager.getConnection(
32. "jdbc:mysql://localhost/test", "root", "123456");
33. stmt = connection.prepareStatement(sql);
34. rs = stmt.executeQuery();
35. Object c1 = null;
36. ResultSetMetaData rsmd = rs.getMetaData();//获得元数据
37. int columnCount = rsmd.getColumnCount();//获得查询的列数个数
38. while (rs.next()) {
39. c1 = Class.forName(className).newInstance();//根据String型的类名，得到一个Object
40. for (int i = 1; i &lt;= columnCount; i++) {//循环设置该类的set方法的相关属性
41. Method m = c1.getClass().getMethod(
42. getSetMethodName(rsmd.getColumnName(i)),
43. Class.forName(rsmd.getColumnClassName(i)));//获得方法
44. m.invoke(c1, rs.getObject(rsmd.getColumnName(i)));//设置set，此处用ResultSet.getObject(String s)方法
45. }
46. paraList.add(c1);//增加到List中
47. }
48. Person p = (Person) paraList.get(0);
49. System.out.println(p.getName());
50. } catch (SQLException ex) {
51. ex.printStackTrace();
52. } catch (ClassNotFoundException e) {
53. e.printStackTrace();
54. } catch (NoSuchMethodException e) {
55. e.printStackTrace();
56. } catch (InvocationTargetException e) {
57. e.printStackTrace();
58. } catch (IllegalAccessException e) {
59. e.printStackTrace();
60. } catch (InstantiationException e) {
61. e.printStackTrace();
62. } finally {
63. try {
64. rs.close();
65. rs = null;
66. } catch (Exception ex) {
67. }
68. try {
69. stmt.close();
70. stmt = null;
71. } catch (Exception ex) {
72. }
73. }
74. try {
75. connection.close();
76. connection = null;
77. } catch (Exception ex) {
78. }
79. return paraList;
80. }
81. }