【Java开源代码栏目提醒】:网学会员为需要Java开源代码的朋友们搜集整理了ConnectManager.java相关资料,希望对各位网友有所帮助!
package cn.com.chengang.sms.db;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import org.eclipse.jface.preference.IPreferenceStore;
import cn.com.chengang.sms.Activator;
import cn.com.chengang.sms.preferences.DBPreferencePage;
public class ConnectManager {
private static Connection con;
private ConnectManager() {}
public static Connection getConnection() throws SQLException {
if (con != null && !con.isClosed())// 不为空且没关闭
return con;
// 由首选项的设置获得连接
IPreferenceStore ps = Activator.getDefault().getPreferenceStore();
String className = ps.getString(DBPreferencePage.CLASSNAME_KEY);
String url = ps.getString(DBPreferencePage.URL_KEY);
String username = ps.getString(DBPreferencePage.USERNAME_KEY);
String password = ps.getString(DBPreferencePage.PASSWORD_KEY);
// 生成一个数据库连接
try {
Class.forName(className);
con = DriverManager.getConnection(url, username, password);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return con;
}
// 提供一个真正关闭Connection的方法
public static void closeConnection() {
if (con == null)
return;
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
con = null;
}
}