zoukankan      html  css  js  c++  java
  • 数据库连接工具类——包含取得连接和关闭资源 ConnUtil.java

    1. package com.util;  
    2.   
    3. import java.sql.Connection;  
    4. import java.sql.DriverManager;  
    5. import java.sql.PreparedStatement;  
    6. import java.sql.ResultSet;  
    7. import java.sql.SQLException;  
    8.   
    9.   
    10. /**  
    11.  * @className: ConnUtil.java 
    12.  * @classDescription: 数据库连接工具类——包含取得连接和关闭资源  
    13.  * @function:  
    14.  * @author: Wentasy 
    15.  * @createTime: 2012-9-24 上午11:51:15 
    16.  * @modifyTime:  
    17.  * @modifyReason:  
    18.  * @since: JDK 1.6 
    19.  */  
    20. public class ConnUtil {  
    21.     public static final String url = "jdbc:mysql://XXX.XXX.XXX.XXX:3306/dbadapter";  
    22.     public static final String user = "root";  
    23.     public static final String password = "XXXXXX";  
    24.       
    25.     /** 
    26.      * 得到连接 
    27.      * @return 
    28.      * @throws SQLException 
    29.      * @throws ClassNotFoundException 
    30.      */  
    31.     public static Connection establishConn() throws SQLException,ClassNotFoundException{  
    32.         Class.forName("com.mysql.jdbc.Driver");  
    33.         return DriverManager.getConnection(url, user, password);  
    34.     }  
    35.       
    36.     /** 
    37.      * 关闭连接 
    38.      * @param conn 
    39.      * @throws SQLException 
    40.      */  
    41.     public static void close(Connection conn) throws SQLException{  
    42.         if(conn != null){  
    43.             conn.close();  
    44.             conn = null;  
    45.         }  
    46.     }  
    47.       
    48.     /** 
    49.      * 关闭PreparedStatement 
    50.      * @param pstmt 
    51.      * @throws SQLException 
    52.      */  
    53.     public static void close(PreparedStatement pstmt) throws SQLException{  
    54.         if(pstmt != null){  
    55.             pstmt.close();  
    56.             pstmt = null;  
    57.         }  
    58.     }  
    59.       
    60.     /** 
    61.      * 关闭结果集 
    62.      * @param rs 
    63.      * @throws SQLException 
    64.      */  
    65.     public static void close(ResultSet rs) throws SQLException{  
    66.         if(rs != null){  
    67.             rs.close();  
    68.             rs = null;  
    69.         }  
    70.     }  
    71. }  
    作者:候鸟
    出处:http://www.cnblogs.com/swite/
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
    如果文中有什么错误,欢迎指出。以免更多的人被误导。
    分享到: 更多
  • 相关阅读:
    写给自己的话
    软件开发之技能梳理
    《创新者的窘境》读书笔记
    我的四年踩坑史以及思考
    认识问题和求解问题的一种思考框架
    《时间的秩序》读书笔记
    从JSON中自动生成对应的对象模型
    考考你:一道题引发的小思考
    哈!如果一生只如花样短暂
    使用正则表达式抽取所需文本
  • 原文地址:https://www.cnblogs.com/swite/p/5168678.html
Copyright © 2011-2022 走看看