java常用的连接数据库的jdbc

 1 package common;
 2 
 3 import java.sql.*;
 4 
 5 public class DBConnect {
 6     
 7     private Connection conn = null;
 8     private Statement  stmt  = null;
 9     private ResultSet  rs    = null;
10     private PreparedStatement ps = null;
11 
12     public DBConnect()
13     {
14         try
15         {    
16             Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
17             conn = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databasename=Test", "sa", "123456");
18             stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
19            
20         }
21         catch (SQLException ex)
22         {
23             System.out.println(ex.getMessage() + "路径错误");
24         }
25         catch (ClassNotFoundException ex)
26         {
27             System.out.println(ex.getMessage() + "驱动错误");
28         }
29     }
30 
31     
32     public PreparedStatement getPs(String sql) throws SQLException {
33         try {
34             ps = conn.prepareStatement(sql);
35             conn.commit();
36             return ps;
37         } catch (Exception e) {
38             //conn.rollback();
39             e.printStackTrace();
40             return ps;
41         }
42     }
43     public ResultSet executeQuery(String ssql) throws SQLException{
44        try{
45            rs = stmt.executeQuery(ssql);
46            return rs;
47 
48        }
49        catch(SQLException se){
50            //conn.rollback();
51            System.out.println("DBBean.executeQuery() ERROR:"+se.getMessage());
52        }
53        return rs;
54    }
55    public int executeUpdate(String ssql) throws SQLException{
56         int iupdate = 0;
57         try{
58             iupdate = stmt.executeUpdate(ssql);
59             return iupdate;
60         }
61         catch(SQLException se){
62             //conn.rollback();
63             System.out.println("DBBean.executeUpdate() ERROR:"+se.getMessage());
64         }
65         return iupdate;
66    }
67    public void free() throws SQLException{
68        try{
69            if(rs   != null) rs.close();
70            if(stmt != null) stmt.close();
71            if(conn != null) conn.close();
72        }
73        catch(SQLException se){
74            System.out.println("DBBean.free() ERROR:"+se.getMessage());
75        }
76    }
77 
78 
79     public Connection getConnection() {
80         return conn;
81     }
82 }

java常用的连接数据库的jdbc,古老的榕树,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。