最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
简单的数据库连接工厂实现
时间:2022-07-02 18:16:18 编辑:袖梨 来源:一聚教程网
我看过很多数据库连接的代码,大部分都存在问题,有的甚至完全不可用,这里给出一个数据库连接工厂,给出了jdbc1和jdbc2的实现,仅供参考!
public class ConnectionFactory_JDBC1{
private static String url="jdbc:oracle:thin:@218.12.7.35:1521:myorcl";
private static String user="developer";
private static String password="developer";
static{
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
}
catch(ClassNotFoundException e){
throw new RuntimeException("无法加载数据库驱动!");
}
}
static Connection getConnection() throws SQLException {
return DriverManager.getConnection(url,user,password);
}
public static void closeConnection(Connection conn){
if (conn != null) {
try {
conn.close();
}
catch (SQLException e) {
//没有必要处理
}
}
}
}
上面连接的是oracle数据库,当然这里用户名和密码以及url你也可以通过配置文件获得,虽然只有短短的几行
代码,对于新手,要完全理解也不是很容易的事,如果可能尽量使用JDBC2方法。
public class ConnectionFactory_JDBC2{
private static String dbName="jdbc/mydb";
private static DataSource ds;
static{
try{
Context ctx=new InitialContext();
ds = (DataSource)ctx.lookup(dbName);
}
catch(NamingException e){
throw new RuntimeException("无法获得数据源!");
}
}
public static Connection getConnection() throws SQLException {
return ds.getConnection();
}
public static void closeConnection(Connection conn){
if (conn != null) {
public class ConnectionFactory_JDBC1{
private static String url="jdbc:oracle:thin:@218.12.7.35:1521:myorcl";
private static String user="developer";
private static String password="developer";
static{
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
}
catch(ClassNotFoundException e){
throw new RuntimeException("无法加载数据库驱动!");
}
}
static Connection getConnection() throws SQLException {
return DriverManager.getConnection(url,user,password);
}
public static void closeConnection(Connection conn){
if (conn != null) {
try {
conn.close();
}
catch (SQLException e) {
//没有必要处理
}
}
}
}
上面连接的是oracle数据库,当然这里用户名和密码以及url你也可以通过配置文件获得,虽然只有短短的几行
代码,对于新手,要完全理解也不是很容易的事,如果可能尽量使用JDBC2方法。
public class ConnectionFactory_JDBC2{
private static String dbName="jdbc/mydb";
private static DataSource ds;
static{
try{
Context ctx=new InitialContext();
ds = (DataSource)ctx.lookup(dbName);
}
catch(NamingException e){
throw new RuntimeException("无法获得数据源!");
}
}
public static Connection getConnection() throws SQLException {
return ds.getConnection();
}
public static void closeConnection(Connection conn){
if (conn != null) {
相关文章
- 发条总动员金币怎么获取 金币获取攻略 09-18
- 不朽箴言雅典娜怎么培养 雅典娜养成攻略 09-18
- 光隙解语新手十连抽怎么选 新手十连抽角色推荐 09-18
- 地下城堡4汲魂器怎么获得 汲魂器获取攻略 09-18
- 地下城堡4装备怎么搭配 装备搭配推荐 09-18
- 地下城堡4叛教者的圣所怎么打 叛教者的圣所打法教学 09-18