Jdbc连接封装

警告
本文最后更新于 2022-06-24,文中内容可能已过时。

java 的jdbc 连接封装

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.CallableStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.sun.corba.se.spi.orbutil.fsm.Guard.Result;


public class DB {
    // 数据库驱动类
    private final static String DRIVER_NAME = "oracle.jdbc.driver.OracleDriver";
    // 数据库URL地址
    private static final String URL = "jdbc:oracle:thin:@localhost:1521:orcl";
    // 数据库用户名
    private static final String USERNAME = "scott";
    // 密码
    private static final String PASSWORD = "tiger";
    private Connection con = null;
    private PreparedStatement ps = null;
    private ResultSet rs = null;
    static {
        try {
            Class.forName(DRIVER_NAME);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    /**
     * 获得数据库连接
     *
     * @return 数据库连接
     */
    public Connection getConnection() throws ClassNotFoundException,
        SQLException {
            if (con == null) {
                con = DriverManager.getConnection(URL, USERNAME, PASSWORD);
            }
            return con;
        }
    public ResultSet executeQuery(String sql, Object...params) throws ClassNotFoundException, SQLException {
        con = this.getConnection();
        ps = con.prepareStatement(sql);
        for (int i = 0; i < params.length; i++) {
            Object o = params[i];
            if (o instanceof Date) {
                Date d = (Date) o;
                Timestamp t = new Timestamp(d.getTime());
                ps.setTimestamp(i + 1, t);
            } else {
                ps.setObject(i + 1, o);
            }
        }
        rs = ps.executeQuery();
        return rs;
    }
    /**
     * 执行查询操作,返回一个结果接
     *
     * @param sql 要执行的SQL语句
     * @param list SQL参数的集合
     * @return 结果集
     * @throws SQLException
     * @throws ClassNotFoundException
     */
    public ResultSet executeQuery(String sql, List list) throws ClassNotFoundException, SQLException {
        con = this.getConnection();
        // 获得预编译语句对象
        ps = con.prepareStatement(sql);
        // 传递参数
        if (list != null) {
            for (int i = 0; i < list.size(); i++) {
                Object o = list.get(i);
                if (o instanceof Date) {
                    Date d = (Date) o;
                    Timestamp t = new Timestamp(d.getTime());
                    ps.setTimestamp(i + 1, t);
                } else {
                    ps.setObject(i + 1, o);
                }
            }
        }
        rs = ps.executeQuery();
        return rs;
    }
    public int executeUpdate(String sql, Object...params) throws ClassNotFoundException, SQLException {
        con = this.getConnection();
        ps = con.prepareStatement(sql);
        for (int i = 0; i < params.length; i++) {
            Object o = params[i];
            if (o instanceof Date) {
                Date d = (Date) o;
                Timestamp t = new Timestamp(d.getTime());
                ps.setTimestamp(i + 1, t);
            } else {
                ps.setObject(i + 1, o);
            }
        }
        return ps.executeUpdate();
    }
    /**
     * 执行增删改语句,返回受影响的行数
     * @param sql sql语句
     * @param list sql语句的参数集合
     */
    public int executeUpdate(String sql, List list) throws ClassNotFoundException, SQLException {
        con = this.getConnection();
        ps = con.prepareStatement(sql);
        if (list != null) {
            for (int i = 0; i < list.size(); i++) {
                Object o = list.get(i);
                if (o instanceof Date) {
                    Date d = (Date) o;
                    Timestamp t = new Timestamp(d.getTime());
                    ps.setTimestamp(i + 1, t);
                } else {
                    ps.setObject(i + 1, o);
                }
            }
        }
        return ps.executeUpdate();
    }

   /**
     * 无参数的存储过程
     *
     * @throws SQLException
     * @throws ClassNotFoundException
     */
     public void prepareCall(String storename, Object... params)
                 throws ClassNotFoundException, SQLException {
          con = this.getConnection();
          String str = " call "+ storename;
          cs = con.prepareCall(str);
           for (int i = 0; i < params.length; i++) {
                Object o = params[i];
                 if (o instanceof Date) {
                      Date d = (Date) o;
                      Timestamp t = new Timestamp(d.getTime());
                      cs.setTimestamp(i + 1, t);
                } else {
                      cs.setObject(i + 1, o);
                }
          }

          cs.execute();
    }

     /**
     * 调用有输出参数 (输出参数类型只能为Stirng类型的数据)的存储过程
     *
     * @throws List<Integer> 指定注册类型
     * @throws SQLException
     * @throws ClassNotFoundException
     */
     public List<String> prepareCall(String storename, List<Integer> list,
                Object.. . params) throws ClassNotFoundException, SQLException {
          con = this.getConnection();
          String str = " call "+ storename;
          cs = con.prepareCall(str);
          List<Integer> klist = new ArrayList<Integer>();
          List<String> relist = new ArrayList<String>();
           if (params.length != 0) {
                 for (int i = 0; i < params.length; i++) {
                      Object o = params[i];
                       if (o instanceof Date) {
                            Date d = (Date) o;
                            Timestamp t = new Timestamp(d.getTime());
                            cs.setTimestamp(i + 1, t);
                      } else {
                            cs.setObject(i + 1, o);
                      }

                       if (params.length - 1 == i && list.size() != 0) {

                             for (int k = 0; k < list.size(); k++) {
                                  cs.registerOutParameter((i + (k + 2)), list.get(k));
                                  klist.add(i+(k+ 2));
                            }

                      }
                }
          }
          cs.execute();
           for(int i = 0;i<klist.size();i++){
                relist.add(cs.getString(klist.get(i)));
          }
           return relist;
    }
    
    /**
     * 关闭连接
     */
    public void close() {
        try {
            if (rs != null) {
                rs.close();
            }
            if (ps != null) {
                ps.close();
            }
            if (con != null) {
                con.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    
    public static void main(String[] args) {
        DB db = new DB();
        String sql = "insert into tab_message values(mesid_seq.nextval,?,?,?,sysdate,0)";
        try {
            db.executeUpdate(sql, "短信内容", "zhangsan", "admin");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            db.close();
        }
    }
}

ODBC 连接配置

ODBC配置:开始–>管理工具 –>数据源–> 用户DSN–>添加 –>选择Oracle in OraDb10g_home1–>完成
Data Source Name中填JdbcOdbc
Description为描述可不填
TNS Service Name中选择Oracle
User ID中填你要使用的数据库中的用户
完成配置后确定
Java文件中需要配置的东西: 定义三个值 :

1
2
3
Connection con = null;
PreparedStatement pst = null;
ResultSet rs = null;

下面的是需要处理异常的代码段:

1
2
3
4
5
6
7
8
9
Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver" );
String url = "jdbc:odbc:JdbcOdbc" ;
con = DriverManager.getConnection(url, "cxd", "cxd" );
String sql = "select * from code where username ='name' and userpassword ='password' ";
pst = con.prepareStatement(sql);
rs = pst.executeQuery(); //执行查询操作
String sql = "delete from name ";
pst = con.prepareStatement(sql);
pst.executeUpdate(); //执行删除操作<增删改都使用它>

//任何时候都要进行关闭

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
if (rs != null) {
              rs.close();
        }
         if (pst != null) {
              pst.close();
        }
         if (con != null) {
              con.close();
        }
  } catch (SQLException e) {
        e.printStackTrace();
  }