1 import java.sql.Connection;
2 import java.sql.DriverManager;
3 import java.sql.ResultSet;
4 import java.sql.SQLException;
5 import java.sql.Statement;
6
7 public class ConnectionUtils {
8
9 private static String url = "";
10 private static String username = "";
11 private static String password = "";
12
13 static{
14 try {
15 String[] str = PropertyUtils.read("dbconn.properties");
16 if(str != null && str.length>0){
17 url = str[0];
18 username = str[1];
19 password = str[2];
20 }
21 } catch (Exception e) {
22 e.printStackTrace();
23 }
24 }
25 /***
26 * 得到连接
27 * @return
28 */
29 public static Connection getConnection(){
30 Connection conn = null;
31 try {
32 Class.forName("com.mysql.jdbc.Driver");
33 conn = DriverManager.getConnection(url, username, password);
34 } catch (SQLException e) {
35 e.printStackTrace();
36 } catch (ClassNotFoundException e) {
37 e.printStackTrace();
38 }
39 return conn;
40
41 }
42
43 public static void closeConnection(Connection conn,Statement st,ResultSet rs){
44 if(rs != null){
45 try {
46 rs.close();
47 } catch (SQLException e) {
48 e.printStackTrace();
49 }
50 }
51 if(st != null){
52 try {
53 st.close();
54 } catch (SQLException e) {
55 e.printStackTrace();
56 }
57 }
58 if(conn != null){
59 try {
60 conn.close();
61 } catch (SQLException e) {
62 e.printStackTrace();
63 }
64 }
65 }
66
67 public static void main(String[]args){
68 Connection con = ConnectionUtils.getConnection();
69 System.out.println(con);
70 }
71 }