1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.hadoop.chukwa.util;
19
20 import java.sql.Connection;
21 import java.sql.DriverManager;
22 import java.sql.SQLException;
23 import java.util.Properties;
24
25 public class DriverManagerUtil {
26
27 @SuppressWarnings("unchecked")
28 public static Class loadDriver() throws ClassNotFoundException {
29 String jdbcDriver = System.getenv("JDBC_DRIVER");
30 if(jdbcDriver == null) {
31 jdbcDriver = "com.mysql.jdbc.Driver";
32 }
33 return Class.forName(jdbcDriver);
34 }
35
36 public static Connection getConnection(String url) throws SQLException {
37 ConnectionInfo info = new ConnectionInfo(url);
38 return DriverManager.getConnection(info.getUri(), info.getProperties());
39 }
40
41 public static class ConnectionInfo {
42 private Properties properties = new Properties();
43 private String uri = null;
44
45 public ConnectionInfo(String url) {
46 int pos = url.indexOf('?');
47 if(pos == -1) {
48 uri = url;
49 } else {
50 uri = url.substring(0, pos);
51 String[] paras = url.substring(pos + 1).split("&");
52 for(String s : paras) {
53 if(s==null || s.length()==0) {
54 continue;
55 }
56 String[] kv = s.split("=");
57 if(kv.length > 1) {
58 properties.put(kv[0], kv[1]);
59 }
60 else {
61 properties.put(kv[0], "");
62 }
63 }
64 }
65 }
66
67 public Properties getProperties() {
68 return properties;
69 }
70
71 public String getUri() {
72 return uri;
73 }
74 }
75 }