公司的报表需要使用 connection ,同事使用的是建立一个类来获得Connection对象。如下:
public class JDBCConnection {
public static String driver = "com.mysql.jdbc.Driver";
public static String url = "jdbc:mysql://192.168.4.52/cms";
public static String user = "root";
public static String password = "password";
public static Connection getConnection() throws ClassNotFoundException,
SQLException {
Class.forName(driver);
Connection conn = DriverManager.getConnection(url, user, password);
return conn;
}
}
我们现在使用的是 Hibernate,这样的话,修改数据源不方便。
我开始使用了直接从Hibernate当中返回Connection,如下:
Session session = HibernateSessionFactory.getSession();
try {
conn = session.connection();
} catch (Exception e) {
throw new HibernateException(e);
} finally {
HibernateSessionFactory.closeSession();
}
但是发现该数据源无法给报表系统正常使用,
最后想:干脆Connection还是使用他原来的方式。就连接信息从Hibernate当中读取。
最后修改成了如下方式:
Properties properties = HibernateSessionFactory.getConfiguration().getProperties();
String driver = properties.getProperty("connection.driver_class");//"com.mysql.jdbc.Driver";
String url = properties.getProperty("connection.url");//"jdbc:mysql://192.168.4.52/cms";
String user = properties.getProperty("connection.username");//"root";
String password = properties.getProperty("connection.password");//"password";
Class.forName(driver);
Connection conn = DriverManager.getConnection(url, user, password);
运行成功!
如果大家有没有什么更好的方法解决,请回复我。