免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1192 | 回复: 0
打印 上一主题 下一主题

最精简实用的jdbc工具类 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2015-07-02 09:30 |只看该作者 |倒序浏览
java对JDBC的封装,操作起来更方便

IResultSetCall.java
  1. import java.sql.ResultSet;
  2. import java.sql.SQLException;

  3. public interface IResultSetCall<T> {

  4.     public T invoke(ResultSet rs) throws SQLException;

  5. }
复制代码
DBUtil.java
  1. import java.io.IOException;
  2. import java.lang.reflect.Constructor;
  3. import java.lang.reflect.Field;
  4. import java.sql.CallableStatement;
  5. import java.sql.Connection;
  6. import java.sql.DriverManager;
  7. import java.sql.PreparedStatement;
  8. import java.sql.ResultSet;
  9. import java.sql.ResultSetMetaData;
  10. import java.sql.SQLException;
  11. import java.sql.Statement;
  12. import java.sql.Time;
  13. import java.util.ArrayList;
  14. import java.util.Date;
  15. import java.util.HashMap;
  16. import java.util.List;
  17. import java.util.Map;
  18. import java.util.Properties;

  19. import oracle.jdbc.OracleTypes;
  20. import util.db.test.DBUtilTest;

  21. /**
  22. *
  23. * DBUtil,数据库访问工具类<br/>
  24. * 对应测试类: {@link DBUtilTest}
  25. * @preserve all
  26. */
  27. public class DBUtil {

  28.     private static Connection con = null;

  29.     public static Connection openConnection() throws SQLException, ClassNotFoundException, IOException {
  30.         if (null == con || con.isClosed()) {
  31.             Properties p = new Properties();
  32.             p.load(DBUtil.class.getResourceAsStream("/config-db.properties"));
  33.             Class.forName(p.getProperty("db_driver"));
  34.             con = DriverManager.getConnection(p.getProperty("db_url"), p.getProperty("db_username"),
  35.                     p.getProperty("db_password"));
  36.         }
  37.         return con;
  38.     }

  39.     public static void closeConnection() throws SQLException {
  40.         try {
  41.             if (null != con)
  42.                 con.close();
  43.         } finally {
  44.             con = null;
  45.             System.gc();
  46.         }
  47.     }

  48.     public static List<Map<String, Object>> queryMapList(Connection con, String sql) throws SQLException,
  49.             InstantiationException, IllegalAccessException {
  50.         List<Map<String, Object>> lists = new ArrayList<Map<String, Object>>();
  51.         Statement preStmt = null;
  52.         ResultSet rs = null;
  53.         try {
  54.             preStmt = con.createStatement();
  55.             rs = preStmt.executeQuery(sql);
  56.             ResultSetMetaData rsmd = rs.getMetaData();
  57.             int columnCount = rsmd.getColumnCount();
  58.             while (null != rs && rs.next()) {
  59.                 Map<String, Object> map = new HashMap<String, Object>();
  60.                 for (int i = 0; i < columnCount; i++) {
  61.                     String name = rsmd.getColumnName(i + 1);
  62.                     Object value = rs.getObject(name);
  63.                     map.put(name, value);
  64.                 }
  65.                 lists.add(map);
  66.             }
  67.         } finally {
  68.             if (null != rs)
  69.                 rs.close();
  70.             if (null != preStmt)
  71.                 preStmt.close();
  72.         }
  73.         return lists;
  74.     }

  75.     public static List<Map<String, Object>> queryMapList(Connection con, String sql, Object... params)
  76.             throws SQLException, InstantiationException, IllegalAccessException {
  77.         List<Map<String, Object>> lists = new ArrayList<Map<String, Object>>();
  78.         PreparedStatement preStmt = null;
  79.         ResultSet rs = null;
  80.         try {
  81.             preStmt = con.prepareStatement(sql);
  82.             for (int i = 0; i < params.length; i++)
  83.                 preStmt.setObject(i + 1, params[i]);// 下标从1开始
  84.             rs = preStmt.executeQuery();
  85.             ResultSetMetaData rsmd = rs.getMetaData();
  86.             int columnCount = rsmd.getColumnCount();
  87.             while (null != rs && rs.next()) {
  88.                 Map<String, Object> map = new HashMap<String, Object>();
  89.                 for (int i = 0; i < columnCount; i++) {
  90.                     String name = rsmd.getColumnName(i + 1);
  91.                     Object value = rs.getObject(name);
  92.                     map.put(name, value);
  93.                 }
  94.                 lists.add(map);
  95.             }
  96.         } finally {
  97.             if (null != rs)
  98.                 rs.close();
  99.             if (null != preStmt)
  100.                 preStmt.close();
  101.         }
  102.         return lists;
  103.     }

  104.     public static <T> List<T> queryBeanList(Connection con, String sql, Class<T> beanClass) throws SQLException,
  105.             InstantiationException, IllegalAccessException {
  106.         List<T> lists = new ArrayList<T>();
  107.         Statement stmt = null;
  108.         ResultSet rs = null;
  109.         Field[] fields = null;
  110.         try {
  111.             stmt = con.createStatement();
  112.             rs = stmt.executeQuery(sql);
  113.             fields = beanClass.getDeclaredFields();
  114.             for (Field f : fields)
  115.                 f.setAccessible(true);
  116.             while (null != rs && rs.next()) {
  117.                 T t = beanClass.newInstance();
  118.                 for (Field f : fields) {
  119.                     String name = f.getName();
  120.                     try {
  121.                         Object value = rs.getObject(name);
  122.                         setValue(t, f, value);
  123.                     } catch (Exception e) {
  124.                     }
  125.                 }
  126.                 lists.add(t);
  127.             }
  128.         } finally {
  129.             if (null != rs)
  130.                 rs.close();
  131.             if (null != stmt)
  132.                 stmt.close();
  133.         }
  134.         return lists;
  135.     }

  136.     public static <T> List<T> queryBeanList(Connection con, String sql, Class<T> beanClass, Object... params)
  137.             throws SQLException, InstantiationException, IllegalAccessException {
  138.         List<T> lists = new ArrayList<T>();
  139.         PreparedStatement preStmt = null;
  140.         ResultSet rs = null;
  141.         Field[] fields = null;
  142.         try {
  143.             preStmt = con.prepareStatement(sql);
  144.             for (int i = 0; i < params.length; i++)
  145.                 preStmt.setObject(i + 1, params[i]);// 下标从1开始
  146.             rs = preStmt.executeQuery();
  147.             fields = beanClass.getDeclaredFields();
  148.             for (Field f : fields)
  149.                 f.setAccessible(true);
  150.             while (null != rs && rs.next()) {
  151.                 T t = beanClass.newInstance();
  152.                 for (Field f : fields) {
  153.                     String name = f.getName();
  154.                     try {
  155.                         Object value = rs.getObject(name);
  156.                         setValue(t, f, value);
  157.                     } catch (Exception e) {
  158.                     }
  159.                 }
  160.                 lists.add(t);
  161.             }
  162.         } finally {
  163.             if (null != rs)
  164.                 rs.close();
  165.             if (null != preStmt)
  166.                 preStmt.close();
  167.         }
  168.         return lists;
  169.     }

  170.     public static <T> List<T> queryBeanList(Connection con, String sql, IResultSetCall<T> qdi) throws SQLException {
  171.         List<T> lists = new ArrayList<T>();
  172.         Statement stmt = null;
  173.         ResultSet rs = null;
  174.         try {
  175.             stmt = con.createStatement();
  176.             rs = stmt.executeQuery(sql);
  177.             while (null != rs && rs.next())
  178.                 lists.add(qdi.invoke(rs));
  179.         } finally {
  180.             if (null != rs)
  181.                 rs.close();
  182.             if (null != stmt)
  183.                 stmt.close();
  184.         }
  185.         return lists;
  186.     }

  187.     public static <T> List<T> queryBeanList(Connection con, String sql, IResultSetCall<T> qdi, Object... params)
  188.             throws SQLException {
  189.         List<T> lists = new ArrayList<T>();
  190.         PreparedStatement preStmt = null;
  191.         ResultSet rs = null;
  192.         try {
  193.             preStmt = con.prepareStatement(sql);
  194.             for (int i = 0; i < params.length; i++)
  195.                 preStmt.setObject(i + 1, params[i]);
  196.             rs = preStmt.executeQuery();
  197.             while (null != rs && rs.next())
  198.                 lists.add(qdi.invoke(rs));
  199.         } finally {
  200.             if (null != rs)
  201.                 rs.close();
  202.             if (null != preStmt)
  203.                 preStmt.close();
  204.         }
  205.         return lists;
  206.     }

  207.     public static <T> T queryBean(Connection con, String sql, Class<T> beanClass) throws SQLException,
  208.             InstantiationException, IllegalAccessException {
  209.         List<T> lists = queryBeanList(con, sql, beanClass);
  210.         if (lists.size() != 1)
  211.             throw new SQLException("SqlError:期待一行返回值,却返回了太多行!");
  212.         return lists.get(0);
  213.     }

  214.     public static <T> T queryBean(Connection con, String sql, Class<T> beanClass, Object... params)
  215.             throws SQLException, InstantiationException, IllegalAccessException {
  216.         List<T> lists = queryBeanList(con, sql, beanClass, params);
  217.         if (lists.size() != 1)
  218.             throw new SQLException("SqlError:期待一行返回值,却返回了太多行!");
  219.         return lists.get(0);
  220.     }

  221.     public static <T> List<T> queryObjectList(Connection con, String sql, Class<T> objClass) throws SQLException,
  222.             InstantiationException, IllegalAccessException {
  223.         List<T> lists = new ArrayList<T>();
  224.         Statement stmt = null;
  225.         ResultSet rs = null;
  226.         try {
  227.             stmt = con.createStatement();
  228.             rs = stmt.executeQuery(sql);
  229.             label: while (null != rs && rs.next()) {
  230.                 Constructor<?>[] constor = objClass.getConstructors();
  231.                 for (Constructor<?> c : constor) {
  232.                     Object value = rs.getObject(1);
  233.                     try {
  234.                         lists.add((T) c.newInstance(value));
  235.                         continue label;
  236.                     } catch (Exception e) {
  237.                     }
  238.                 }
  239.             }
  240.         } finally {
  241.             if (null != rs)
  242.                 rs.close();
  243.             if (null != stmt)
  244.                 stmt.close();
  245.         }
  246.         return lists;
  247.     }

  248.     public static <T> List<T> queryObjectList(Connection con, String sql, Class<T> objClass, Object... params)
  249.             throws SQLException, InstantiationException, IllegalAccessException {
  250.         List<T> lists = new ArrayList<T>();
  251.         PreparedStatement preStmt = null;
  252.         ResultSet rs = null;
  253.         try {
  254.             preStmt = con.prepareStatement(sql);
  255.             for (int i = 0; i < params.length; i++)
  256.                 preStmt.setObject(i + 1, params[i]);
  257.             rs = preStmt.executeQuery();
  258.             label: while (null != rs && rs.next()) {
  259.                 Constructor<?>[] constor = objClass.getConstructors();
  260.                 for (Constructor<?> c : constor) {
  261.                     String value = rs.getObject(1).toString();
  262.                     try {
  263.                         T t = (T) c.newInstance(value);
  264.                         lists.add(t);
  265.                         continue label;
  266.                     } catch (Exception e) {
  267.                     }
  268.                 }
  269.             }
  270.         } finally {
  271.             if (null != rs)
  272.                 rs.close();
  273.             if (null != preStmt)
  274.                 preStmt.close();
  275.         }
  276.         return lists;
  277.     }

  278.     public static <T> T queryObject(Connection con, String sql, Class<T> objClass) throws SQLException,
  279.             InstantiationException, IllegalAccessException {
  280.         List<T> lists = queryObjectList(con, sql, objClass);
  281.         if (lists.size() != 1)
  282.             throw new SQLException("SqlError:期待一行返回值,却返回了太多行!");
  283.         return lists.get(0);
  284.     }

  285.     public static <T> T queryObject(Connection con, String sql, Class<T> objClass, Object... params)
  286.             throws SQLException, InstantiationException, IllegalAccessException {
  287.         List<T> lists = queryObjectList(con, sql, objClass, params);
  288.         if (lists.size() != 1)
  289.             throw new SQLException("SqlError:期待一行返回值,却返回了太多行!");
  290.         return lists.get(0);
  291.     }

  292.     public static int execute(Connection con, String sql) throws SQLException {
  293.         Statement stmt = null;
  294.         try {
  295.             stmt = con.createStatement();
  296.             return stmt.executeUpdate(sql);
  297.         } finally {
  298.             if (null != stmt)
  299.                 stmt.close();
  300.         }
  301.     }

  302.     public static int execute(Connection con, String sql, Object... params) throws SQLException {
  303.         PreparedStatement preStmt = null;
  304.         try {
  305.             preStmt = con.prepareStatement(sql);
  306.             for (int i = 0; i < params.length; i++)
  307.                 preStmt.setObject(i + 1, params[i]);// 下标从1开始
  308.             return preStmt.executeUpdate();
  309.         } finally {
  310.             if (null != preStmt)
  311.                 preStmt.close();
  312.         }
  313.     }

  314.     public static int[] executeAsBatch(Connection con, List<String> sqlList) throws SQLException {
  315.         return executeAsBatch(con, sqlList.toArray(new String[] {}));
  316.     }

  317.     public static int[] executeAsBatch(Connection con, String[] sqlArray) throws SQLException {
  318.         Statement stmt = null;
  319.         try {
  320.             stmt = con.createStatement();
  321.             for (String sql : sqlArray) {
  322.                 stmt.addBatch(sql);
  323.             }
  324.             return stmt.executeBatch();
  325.         } finally {
  326.             if (null != stmt) {
  327.                 stmt.close();
  328.             }
  329.         }
  330.     }

  331.     public static int[] executeAsBatch(Connection con, String sql, Object[][] params) throws SQLException {
  332.         PreparedStatement preStmt = null;
  333.         try {
  334.             preStmt = con.prepareStatement(sql);
  335.             for (int i = 0; i < params.length; i++) {
  336.                 Object[] rowParams = params[i];
  337.                 for (int k = 0; k < rowParams.length; k++) {
  338.                     Object obj = rowParams[k];
  339.                     preStmt.setObject(k + 1, obj);
  340.                 }
  341.                 preStmt.addBatch();
  342.             }
  343.             return preStmt.executeBatch();
  344.         } finally {
  345.             if (null != preStmt) {
  346.                 preStmt.close();
  347.             }
  348.         }
  349.     }

  350.     private static <T> void setValue(T t, Field f, Object value) throws IllegalAccessException {
  351.         // TODO 以数据库类型为准绳,还是以java数据类型为准绳?还是混合两种方式?
  352.         if (null == value)
  353.             return;
  354.         String v = value.toString();
  355.         String n = f.getType().getName();
  356.         if ("java.lang.Byte".equals(n) || "byte".equals(n)) {
  357.             f.set(t, Byte.parseByte(v));
  358.         } else if ("java.lang.Short".equals(n) || "short".equals(n)) {
  359.             f.set(t, Short.parseShort(v));
  360.         } else if ("java.lang.Integer".equals(n) || "int".equals(n)) {
  361.             f.set(t, Integer.parseInt(v));
  362.         } else if ("java.lang.Long".equals(n) || "long".equals(n)) {
  363.             f.set(t, Long.parseLong(v));
  364.         } else if ("java.lang.Float".equals(n) || "float".equals(n)) {
  365.             f.set(t, Float.parseFloat(v));
  366.         } else if ("java.lang.Double".equals(n) || "double".equals(n)) {
  367.             f.set(t, Double.parseDouble(v));
  368.         } else if ("java.lang.String".equals(n)) {
  369.             f.set(t, value.toString());
  370.         } else if ("java.lang.Character".equals(n) || "char".equals(n)) {
  371.             f.set(t, (Character) value);
  372.         } else if ("java.lang.Date".equals(n)) {
  373.             f.set(t, new Date(((java.sql.Date) value).getTime()));
  374.         } else if ("java.lang.Timer".equals(n)) {
  375.             f.set(t, new Time(((java.sql.Time) value).getTime()));
  376.         } else if ("java.sql.Timestamp".equals(n)) {
  377.             f.set(t, (java.sql.Timestamp) value);
  378.         } else {
  379.             System.out.println("SqlError:暂时不支持此数据类型,请使用其他类型代替此类型!");
  380.         }
  381.     }

  382.     public static void executeProcedure(Connection con, String procedureName, Object... params) throws SQLException {
  383.         CallableStatement proc = null;
  384.         try {
  385.             proc = con.prepareCall(procedureName);
  386.             for (int i = 0; i < params.length; i++) {
  387.                 proc.setObject(i + 1, params[i]);
  388.             }
  389.             proc.execute();
  390.         } finally {
  391.             if (null != proc)
  392.                 proc.close();
  393.         }
  394.     }

  395.     public static boolean executeProcedureReturnErrorMsg(Connection con, String procedureName, StringBuffer errorMsg,
  396.             Object... params) throws SQLException {
  397.         CallableStatement proc = null;
  398.         try {
  399.             proc = con.prepareCall(procedureName);
  400.             proc.registerOutParameter(1, OracleTypes.VARCHAR);
  401.             for (int i = 0; i < params.length; i++) {
  402.                 proc.setObject(i + 2, params[i]);
  403.             }
  404.             boolean b = proc.execute();
  405.             errorMsg.append(proc.getString(1));
  406.             return b;
  407.         } finally {
  408.             if (null != proc)
  409.                 proc.close();
  410.         }
  411.     }

  412.     public static <T> List<T> executeProcedureReturnCursor(Connection con, String procedureName, Class<T> beanClass,
  413.             Object... params) throws SQLException, InstantiationException, IllegalAccessException {
  414.         List<T> lists = new ArrayList<T>();
  415.         CallableStatement proc = null;
  416.         ResultSet rs = null;
  417.         try {
  418.             proc = con.prepareCall(procedureName);
  419.             proc.registerOutParameter(1, OracleTypes.CURSOR);
  420.             for (int i = 0; i < params.length; i++) {
  421.                 proc.setObject(i + 2, params[i]);
  422.             }
  423.             boolean b = proc.execute();
  424.             if (b) {
  425.                 rs = (ResultSet) proc.getObject(1);
  426.                 while (null != rs && rs.next()) {
  427.                     T t = beanClass.newInstance();
  428.                     Field[] fields = beanClass.getDeclaredFields();
  429.                     for (Field f : fields) {
  430.                         f.setAccessible(true);
  431.                         String name = f.getName();
  432.                         try {
  433.                             Object value = rs.getObject(name);
  434.                             setValue(t, f, value);
  435.                         } catch (Exception e) {
  436.                         }
  437.                     }
  438.                     lists.add(t);
  439.                 }
  440.             }
  441.         } finally {
  442.             if (null != rs)
  443.                 rs.close();
  444.             if (null != proc)
  445.                 proc.close();
  446.         }
  447.         return lists;
  448.     }

  449.     public static <T> List<List<T>> listLimit(List<T> lists, int pageSize) {
  450.         List<List<T>> llists = new ArrayList<List<T>>();
  451.         for (int i = 0; i < lists.size(); i = i + pageSize) {
  452.             try {
  453.                 List<T> list = lists.subList(i, i + pageSize);
  454.                 llists.add(list);
  455.             } catch (IndexOutOfBoundsException e) {
  456.                 List<T> list = lists.subList(i, i + (lists.size() % pageSize));
  457.                 llists.add(list);
  458.             }
  459.         }
  460.         return llists;
  461.     }


  462. }
复制代码
config-db.properties
  1. db_url=jdbc:oracle:thin:@localhost:1521:orcl
  2. db_driver=oracle.jdbc.driver.OracleDriver
  3. db_username=hr
  4. db_password=
复制代码
DBUtilTest.java
  1. import static org.junit.Assert.fail;
  2. import static util.db.DBUtil.executeAsBatch;
  3. import static util.db.DBUtil.executeProcedure;
  4. import static util.db.DBUtil.openConnection;

  5. import java.sql.Connection;
  6. import java.sql.ResultSet;
  7. import java.sql.SQLException;
  8. import java.util.ArrayList;
  9. import java.util.List;
  10. import java.util.Map;
  11. import java.util.Set;

  12. import org.junit.After;
  13. import org.junit.Assert;
  14. import org.junit.Before;
  15. import org.junit.Test;

  16. import util.db.DBUtil;
  17. import util.db.IResultSetCall;

  18. /**
  19. * 注意: 可以替换Employess1为Employess2,看看查询结果有什么区别。。
  20. */
  21. public class DBUtilTest {

  22.     private Connection con = null;

  23.     @Before
  24.     public void setUp() throws Exception {
  25.         try {
  26.             con = DBUtil.openConnection();
  27.         } catch (SQLException e) {
  28.             fail(e.getMessage());
  29.         }
  30.     }

  31.     @After
  32.     public void tearDown() throws Exception {
  33.         try {
  34.             DBUtil.closeConnection();
  35.         } catch (SQLException e) {
  36.             fail(e.getMessage());
  37.         }
  38.     }

  39.     @Test
  40.     public void testQueryBeanListConnectionStringClassOfT() {
  41.         String sql = "SELECT * FROM employees";
  42.         try {
  43.             List<Employees1> emList = DBUtil.queryBeanList(con, sql, Employees1.class);
  44.             print(emList);
  45.         } catch (Exception e) {
  46.             fail(e.getMessage());
  47.         }
  48.     }

  49.     @Test
  50.     public void testQueryBeanListConnectionStringClassOfTObjectArray() {
  51.         String sql = "SELECT * FROM employees t WHERE t.salary > ? and T.JOB_ID = ?";
  52.         try {
  53.             List<Employees1> emList = DBUtil.queryBeanList(con, sql, Employees1.class, 5000, "ST_MAN");
  54.             print(emList);
  55.         } catch (Exception e) {
  56.             fail(e.getMessage());
  57.         }
  58.     }

  59.     @Test
  60.     public void testQueryBeanListConnectionStringIResultSetCallOfTObjectArray() {
  61.         String sql = "SELECT first_name, last_name, salary FROM employees t WHERE t.salary > ? and T.JOB_ID = ?";
  62.         try {
  63.             List<Employees1> emList = DBUtil.queryBeanList(con, sql, new IResultSetCall<Employees1>() {
  64.                 public Employees1 invoke(ResultSet rs) throws SQLException {
  65.                     Employees1 e = new Employees1();
  66.                     e.setFirst_name(rs.getString("first_name"));
  67.                     e.setLast_name(rs.getString("last_name"));
  68.                     e.setSalary(rs.getDouble("salary"));
  69.                     return e;
  70.                 }
  71.             }, 5000, "ST_MAN");
  72.             print(emList);
  73.         } catch (Exception e) {
  74.             e.printStackTrace();
  75.             fail(e.getMessage());
  76.         }
  77.     }

  78.     @Test
  79.     public void testQueryObjectListConnectionStringClassOfT() {
  80.         String sql = "SELECT email FROM employees t";
  81.         try {
  82.             List<String> lists = DBUtil.queryObjectList(con, sql, String.class);
  83.             print(lists);
  84.         } catch (Exception e) {
  85.             fail(e.getMessage());
  86.         }
  87.     }

  88.     @Test
  89.     public void testQueryObjectListConnectionStringClassOfTObjectArray() {
  90.         String sql = "SELECT salary FROM employees t WHERE t.salary > ? and T.JOB_ID = ?";
  91.         try {
  92.             List<Double> lists = DBUtil.queryObjectList(con, sql, Double.class, 2000, "ST_MAN");
  93.             print(lists);
  94.         } catch (Exception e) {
  95.             fail(e.getMessage());
  96.             e.printStackTrace();
  97.         }
  98.     }

  99.     @Test
  100.     public void testQueryBeanConnectionStringClassOfT() {
  101.         String sql = "SELECT * FROM employees t WHERE t.employee_id in (120)";
  102.         try {
  103.             Employees1 emp = DBUtil.queryBean(con, sql, Employees1.class);
  104.             print(emp);
  105.         } catch (Exception e) {
  106.             fail(e.getMessage());
  107.         }
  108.     }

  109.     @Test
  110.     public void testQueryBeanConnectionStringClassOfTObjectArray() {
  111.         String sql = "SELECT * FROM employees t WHERE t.employee_id = ?";
  112.         try {
  113.             Employees1 emp = DBUtil.queryBean(con, sql, Employees1.class, 120);
  114.             print(emp);
  115.         } catch (Exception e) {
  116.             fail(e.getMessage());
  117.         }
  118.     }

  119.     @Test
  120.     public void testQueryObjectConnectionStringClassOfT() {
  121.         String sql = "SELECT email FROM employees t WHERE t.employee_id in (120)";
  122.         try {
  123.             String s = DBUtil.queryObject(con, sql, String.class);
  124.             print(s);
  125.         } catch (Exception e) {
  126.             fail(e.getMessage());
  127.         }
  128.     }

  129.     @Test
  130.     public void testQueryObjectConnectionStringClassOfTObjectArray() {
  131.         String sql = "SELECT salary FROM employees t WHERE t.employee_id in (?)";
  132.         try {
  133.             Double d = DBUtil.queryObject(con, sql, Double.class, 12);
  134.             print(d);
  135.         } catch (Exception e) {
  136.             fail(e.getMessage());
  137.             e.printStackTrace();
  138.         }
  139.     }

  140.     @Test
  141.     public void testExecuteConnectionStringObjectArray() {
  142.         String sql = "UPDATE employees t SET t.salary =? WHERE t.employee_id =?";
  143.         try {
  144.             con.setAutoCommit(false);
  145.             int count = DBUtil.execute(con, sql, 20000, 120);
  146.             Assert.assertTrue(count == 1);
  147.             sql = "SELECT t.salary FROM employees t WHERE t.employee_id =?";
  148.             Double d = DBUtil.queryObject(con, sql, Double.class, 120);
  149.             Assert.assertTrue(d - 20000 == 0);
  150.         } catch (Exception e) {
  151.             e.printStackTrace();
  152.             fail(e.getMessage());
  153.         } finally {
  154.             try {
  155.                 con.rollback();
  156.                 con.setAutoCommit(true);
  157.             } catch (SQLException e) {
  158.                 e.printStackTrace();
  159.             }
  160.         }
  161.     }

  162.     @Test
  163.     public void testQueryMapList() {
  164.         String sql = "SELECT first_name, last_name, salary FROM employees t WHERE t.salary > ? and T.JOB_ID = ?";
  165.         try {
  166.             List<Map<String, Object>> lists = DBUtil.queryMapList(con, sql, 3000, "ST_MAN");
  167.             print(lists);
  168.         } catch (Exception e) {
  169.             e.printStackTrace();
  170.             fail(e.getMessage());
  171.         }
  172.     }

  173.     @Test
  174.     public void testExecuteProcedure() {
  175.         try {
  176.             executeProcedure(openConnection(), "{CALL prc_updatedata_for_daochong(?,?,?,?)}", "3000000993447731",
  177.                     "060000019213", "50", "0010701848");
  178.             System.out.println("执行存储过程更新采购订单表上的数据成功");
  179.         } catch (Exception e) {
  180.             e.printStackTrace();
  181.             fail(e.getMessage());
  182.         }
  183.     }

  184.     @Test
  185.     public void testExecuteAsBatch() {
  186.         try {
  187.             List<String> sqlList = new ArrayList<String>();
  188.             sqlList.add("UPDATE sm_user t SET t.password = 'ok' WHERE t.row_id = '232s43' ");
  189.             sqlList.add("UPDATE sm_user t SET t.password = 'ok' WHERE t.row_id = '232f42' ");
  190.             sqlList.add("UPDATE sm_user t SET t.password = 'ok' WHERE t.row_id = '23g2423' ");
  191.             sqlList.add("UPDATE sm_user t SET t.password = 'ok' WHERE t.row_id = '232434s' ");
  192.             executeAsBatch(openConnection(), sqlList);
  193.         } catch (Exception e) {
  194.             e.printStackTrace();
  195.             fail(e.getMessage());
  196.         }
  197.     }

  198.     @Test
  199.     public void testExecuteAsBatchForPre() {
  200.         try {
  201.             executeAsBatch(con, "UPDATE employees t SET t.first_name = ? WHERE t.last_name = ? ", new Object[][] {
  202.                     { "ok", "235jklsd" }, { "no", "jg4ti324" }, { "no1", "111" }, { "no2", "32423" } });
  203.         } catch (Exception e) {
  204.             e.printStackTrace();
  205.             fail(e.getMessage());
  206.         }
  207.     }

  208.     private void print(Object obj) {
  209.         if (obj instanceof List) {
  210.             List list = (List) obj;
  211.             for (Object o : list) {
  212.                 if (o instanceof Map) {
  213.                     Map<String, Object> map = (Map<String, Object>) o;
  214.                     Set<String> set = map.keySet();
  215.                     for (String key : set) {
  216.                         Object value = map.get(key);
  217.                         System.out.print(key + ":" + value + "\t");
  218.                     }
  219.                     System.out.println();
  220.                 } else {
  221.                     System.out.println(o);
  222.                 }
  223.             }
  224.             System.out.println("总共查询出数据数量是:" + list.size());
  225.         } else {
  226.             System.out.println(obj);
  227.         }
  228.     }

  229. }
复制代码
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP