Jdbc连接mySql数据库

 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 }
View Code
 1 import java.io.InputStream;
 2 import java.util.Properties;
 3 
 4 public class PropertyUtils {
 5     
 6     public static String[] read(String path) throws Exception{
 7         InputStream inStream = PropertyUtils.class.getClassLoader().getResourceAsStream(path);
 8         String[] str = new String[3];
 9         Properties prop = new Properties();
10         prop.load(inStream);
11         String url = (String) prop.get("jdbc.url");
12         String username = (String)prop.get("jdbc.username");
13         String password = (String)prop.get("jdbc.password");
14         str[0] = url;
15         str[1] = username;
16         str[2]= password;
17         return str;
18     }
19 
20 }
View Code

posted @ 2013-09-16 12:54  胖hu  阅读(182)  评论(0编辑  收藏  举报