最新下载
热门教程
- 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) {
相关文章
- 126邮箱快捷登录-126网易邮箱多账号无缝切换 03-28
- 红色沙漠君子之弓怎么获得 君子之弓获取位置参考 03-28
- 淘宝闪购购物车在哪里-淘宝闪购购物车入口怎么打开 03-28
- 洛克王国世界隐藏传送点大全 洛克王国世界全地图秘境传送位置汇总 03-28
- 洛克王国世界圣羽翼王怎么过 圣羽翼王打法思路推荐 03-28
- 毒液突击队尸王打法攻略 毒液突击队尸王Boss通关技巧与阵容搭配 03-28