Java 数据库操作类

 

 1 import java.sql.Connection;
 2 import java.sql.DriverManager;
 3 import java.sql.PreparedStatement;
 4 import java.sql.ResultSet;
 5 import java.sql.SQLException;
 6 
 7 /**********
 8  * 
 9  * @author aq
10  * 
11  */
12 public class DBOper {
13     Connection conn = null;
14     PreparedStatement pstmt = null;
15     ResultSet rs = null;
16 
17     public Connection getConn(String server, String dbname, String user, String pwd)
18             throws ClassNotFoundException, SQLException, InstantiationException, IllegalAccessException {
19         String DRIVER = "com.mysql.jdbc.Driver";
20         String URL = "jdbc:mysql://" + server + ":3306/" + dbname + "?user=" + user + "&password=" + pwd
21                 + "&useUnicode=true&characterEncoding=utf8";
22         Class.forName(DRIVER).newInstance();
23         conn = DriverManager.getConnection(URL);
24         return conn;
25     }
26 
27     public void closeAll() {
28         if (rs != null) {
29             try {
30                 rs.close();
31             } catch (SQLException e) {
32                 e.printStackTrace();
33             }
34         }
35         if (pstmt != null) {
36             try {
37                 pstmt.close();
38             } catch (SQLException e) {
39                 e.printStackTrace();
40             }
41         }
42         if (conn != null) {
43             try {
44                 conn.close();
45             } catch (SQLException e) {
46                 e.printStackTrace();
47             }
48         }
49     }
50 
51     public ResultSet executeQuery(String preparedSql, String[] param) {
52         try {
53             pstmt = conn.prepareStatement(preparedSql);
54             if (param != null) {
55                 for (int i = 0; i < param.length; i++) {
56                     pstmt.setString(i + 1, param[i]);
57                 }
58             }
59             rs = pstmt.executeQuery();
60         } catch (SQLException e) {
61             e.printStackTrace();
62         }
63         return rs;
64     }
65 
66     public int executeUpdate(String preparedSql, String[] param) {
67         int num = 0;
68         try {
69             pstmt = conn.prepareStatement(preparedSql);
70             if (param != null) {
71                 for (int i = 0; i < param.length; i++) {
72                     pstmt.setString(i + 1, param[i]);
73                 }
74             }
75             num = pstmt.executeUpdate();
76         } catch (SQLException e) {
77             e.printStackTrace();
78         }
79         return num;
80     }
81 
82 }

 

转载于:https://www.cnblogs.com/A--Q/p/6137525.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值