Java的sql动态参数

在C#的方法中可以使用params Parameter[] values来动态获取sql语句中的参数值数组。
Java中可以自己封装出一个类似于C#的方法

1、获取结果集

 1     /**
 2      *  获取结果集
 3      * @param sql SQL语句
 4      * @param params SQL语句数据数组
 5      * @return 结果集
 6      */
 7     public static ResultSet getResultSet(String sql,Object[] params) {
 8         ResultSet rs=null;
 9         //从DButil获取连接对象
10         Connection conn=getConnection();
11         try {
12             //获取PreparedStatement对象
13             PreparedStatement ps= conn.prepareStatement(sql);
14             //循环遍历数据数组
15             for(int i=0;i<params.length;i++) {
16                 ps.setObject(i+1, params[i]);
17             }
18             //返回结果集
19             rs=ps.executeQuery();
20         } catch (SQLException e) {
21             // TODO Auto-generated catch block
22             System.out.println(e.getMessage());
23             return rs;
24         }
25         return rs;
26     }

2、执行增删改

 1 /**
 2      * 执行数据库增删改语句
 3      * @param sql 数据库执行语句
 4      * @param params SQL语句数据数组
 5      * @return 受影响行的数量
 6      */
 7     public static int getUpdate(String sql,Object[] params) {
 8         int n=0;
 9         //从DButil获取连接对象
10         Connection conn=getConnection();
11         PreparedStatement ps=null;
12         try {
13             //获取PreparedStatement对象
14              ps= conn.prepareStatement(sql);
15             //循环遍历数据数组
16             for(int i=0;i<params.length;i++) {
17                 ps.setObject(i+1, params[i]);
18             }
19             n=ps.executeUpdate();
20         } catch (SQLException e) {
21             // TODO Auto-generated catch block
22             e.printStackTrace();
23         }
24         return n;
25     } 

 

posted @ 2018-06-28 11:46  黄浩#  阅读(3239)  评论(0编辑  收藏  举报