当前位置: 首页 > 工具软件 > DBConnection > 使用案例 >

dbconn Java_关于java jdbc 数据连接类(dbconnection)

诸葛文博
2023-12-01

package util;

import java.sql.Connection;

import java.sql.Driver;

import java.sql.DriverManager;

public class DBConnection {

/**

* 连接数据库参数

*/

private String  username = "ciss";

private String  password = "ciss";

private String  driverName = "oracle.jdbc.driver.OracleDriver";

private String  url = "jdbc:oracle:thin:@172.29.140.140:1521:ciss";

/**

* 静态实例属性

*/

private static DBConnection dbConn = null;

/**

* 无参构造方法

*/

private DBConnection(){

}

/**

* 静态实例化连接

* @return

*/

public static DBConnection getInstance(){

if(dbConn == null){

dbConn = new DBConnection();

}

return dbConn;

}

/**

* 得到配置文件配置的连接

*

* @return

*/

public Connection getConnection() throws Exception {

try {

return getConnection(driverName, url, username, password);

} catch (Exception e) {

throw new Exception("Fail at create dababase connection!"+ e.getMessage());

}

}

/**

* 得到配置文件配置的连接

*

* @return

*/

public Connection getConnection(String databaseDriver, String url,

String userName, String password) throws Exception {

try {

Driver dbDriver = (Driver) Class.forName(databaseDriver).newInstance();

DriverManager.registerDriver(dbDriver);

return DriverManager.getConnection(url, userName, password);

} catch (Exception e) {

return null;

}

}

public String getUsername() {

return username;

}

public void setUsername(String username) {

this.username = username;

}

public String getPassword() {

return password;

}

public void setPassword(String password) {

this.password = password;

}

public String getDriverName() {

return driverName;

}

public void setDriverName(String driverName) {

this.driverName = driverName;

}

public String getUrl() {

return url;

}

public void setUrl(String url) {

this.url = url;

}

/**

* @param args

*/

public static void main(String[] args) {

try {

Connection conn = new DBConnection().getInstance().getConnection();

if(conn != null){

System.out.println("连接成功!");

}

}catch(Exception e){

e.printStackTrace();

}

}

}

 类似资料: