最新下载
热门教程
- 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) {
相关文章
- 明末渊虚之羽想回原起点要怎么做 原起点传送方法介绍 07-30
- 绝区零插头布强度如何 绝区零插头布强度介绍 07-30
- 柴犬币的今日价格(今天柴犬币的最新价格) 07-30
- 人渣SCUM武器怎么制作 武器制作方法分享 07-30
- 燕云十六声河伯无伤怎么通关 鬼神愁无伤逃课打法攻略 07-30
- 明末渊虚之羽覆羽剑怎么样 覆羽剑武器技能介绍 07-30