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. import java.sql.Statement;  
  7.  
  8. public class DBUtil {  
  9.  
  10. private static Connection con = null;  
  11. private Statement statement;  
  12. private PreparedStatement preparedStatement;  
  13.  
  14. public static final String URL = "jdbc:microsoft:sqlserver://127.0.0.1:1433;DatabaseName=mydb;SelectMethod=cursor";  
  15. public static final String DRIVERNAME = "com.microsoft.jdbc.sqlserver.SQLServerDriver";  
  16. private final static String USERNAME = "sa";  
  17. private final static String PASSWORD = "";  
  18.  
  19. private DBUtil() {  
  20. con = getConnection();  
  21. }  
  22.  
  23. public static synchronized DBUtil getDBInstance() {  
  24. return new DBUtil();  
  25. }  
  26.  
  27. public static synchronized Connection getConnection() {  
  28.  
  29. // 直接连接数据库  
  30.  
  31. try {  
  32. Class.forName(DRIVERNAME).newInstance();  
  33. con = DriverManager.getConnection(URL, USERNAME, PASSWORD);  
  34. con.setAutoCommit(true);  
  35. } catch (Exception ex) {  
  36. System.out.println("数据库加载失败!");  
  37. }  
  38.  
  39. return con;  
  40. }  
  41.  
  42. public Statement getStatement() {  
  43. try {  
  44. con = getConnection();  
  45. statement = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,  
  46. ResultSet.CONCUR_READ_ONLY);  
  47. } catch (Exception e) {  
  48. System.out.println("getStatement Exception");  
  49. System.out.println(e.getMessage());  
  50. }  
  51. return statement;  
  52. }  
  53.  
  54. public PreparedStatement getPreparedStatement(String sql) {  
  55. try {  
  56. con = getConnection();  
  57. preparedStatement = con.prepareStatement(sql);  
  58. } catch (Exception e) {  
  59. System.out.println("getPstmt");  
  60. System.out.println(e.getMessage());  
  61. }  
  62. return preparedStatement;  
  63. }  
  64.  
  65. // 关闭数据库  
  66.  
  67. public void closeConnection() {  
  68. // System.out.println("---------------开始关闭数据库连接------------------");  
  69. try {  
  70. if (statement != null)  
  71. statement.close();  
  72. } catch (Exception e) {  
  73. System.err.println("statement关闭出现异常!");  
  74. }  
  75. try {  
  76. if (preparedStatement != null)  
  77. preparedStatement.close();  
  78. } catch (Exception e) {  
  79. System.err.println("preparedStatement关闭出现异常!");  
  80. }  
  81. if (con != null) {  
  82. try {  
  83. con.close();  
  84. } catch (SQLException e) {  
  85. e.printStackTrace();  
  86. } finally {  
  87. con = null;  
  88. }  
  89. }  
  90. // System.out.println("----------------关闭数据库连接成功!---------------------");  
  91. }  
  92. public static void main(String[] args) {  
  93. new DBUtil();  
  94. }  
  95.  
  96. }