连接mysql,oracle,sqlServer数据库的方式

列举几种常用Jdbc连接配置以及获取sqlSession的方式。
一、最常规的通过Jdbc连接工具类连接(记得导入相应的架包:oJdbc5.jar 或者
mysql-connector-java-5.1.22-bin.jar或者是sqljdbc4.jar)
oracle \mysql\sqlServer

db.properties 配置文件内容:
db.driverClassName=oracle.jdbc.OracleDriver //
db.url=jdbc:oracle:thin:@localhost:1521:xe
//jdbc:sqlserver://localhost;DatabaseName=mysqlServerName —-sqlServer驱动
//jdbc:mysql://localhost/order?characterEncoding=UTF-8 —-mysql驱动,端口3306可加可不加
db.username=root
db.password=root
—————–连接数据库的工具类
public class JdbcUtil {
private static Properties prop = new Properties();
private static final ThreadLocal tdl = new ThreadLocal();
static {
try {
InputStream is = JdbcUtil.class.getResourceAsStream(“/db.properties”);
prop.load(is);
Class.forName(prop.getProperty(“dg.driverClassName”));
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
//获得数据库连接
public static Connection getConn() {
Connection conn = null;
conn = tdl.get();
try {
if (conn == null) {
conn = DriverManager.getConnection(prop.getProperty(“dg.url”),
prop.getProperty(“dg.username”), prop.getProperty(“dg.password”));
tdl.set(conn);
}
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
return conn;
}
//释放连接
public static void releaseConn(Connection conn, PreparedStatement pstm,
ResultSet rs) {
try {
if (conn != null) {
tdl.remove();
conn.close();
}
if (pstm != null) {
pstm.close();
}
if (rs != null) {
rs.close();
}
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
二、通过sqlSession获得连接
(1)hibernate工具类
public class HUtil {
private static SessionFactory sf;
static {
Configuration cfg=new Configuration().configure(“/hibernate.cfg.xml”); //hibernate.cfg.xml文件里面是数据源配置
sf=cfg.buildSessionFactory();
}
public static Session getSession(){
return sf.getCurrentSession();//一定是获得当前的Session保证session的唯一性
}
}
hibernate.cfg.xml文件

你可能感兴趣的:(数据库连接)