jdbc.drivers=oracle.jdbc.driver.OracleDriver
jdbc.url=jdbc:oracle:thin:@localhost:1521:ORCL
jdbc.username=scott
jdbc.password=tiger
package com.util;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
import oracle.sql.CLOB;//对应使用的数据库
public class DatabaseUtil {
private static DatabaseUtil dbUtil;
private String drivers;
private String url;
private String username;
private String password;
//加反斜线就表示在默认包目录,不加则表示在与当前类同路径去查找该属性文件
private static String FILE_PATH_NAME = "/database.properties";
private void init() {
try {
InputStream in = getClass().getResourceAsStream(FILE_PATH_NAME);
Properties props = new Properties();
props.load(in);
in.close();
drivers = props.getProperty("jdbc.drivers");
url = props.getProperty("jdbc.url");
username = props.getProperty("jdbc.username");
password = props.getProperty("jdbc.password");
} catch (IOException e) {
e.printStackTrace();
}
}
private DatabaseUtil() {
init();
}
public static DatabaseUtil getInstance() {
if(dbUtil == null) {
dbUtil = new DatabaseUtil();
}
return dbUtil;
}
public Connection getConnection() {
Connection conn = null;
try {
Class.forName(drivers);
conn = DriverManager.getConnection(url, username, password);
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return conn;
}
}
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<jsp:directive.page import="com.util.DatabaseUtil"/>
<jsp:directive.page import="java.sql.Connection"/>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'connTest.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css" mce_href="styles.css">
-->
</head>
<body>
<%
DatabaseUtil dbUtil = DatabaseUtil.getInstance();
Connection conn = dbUtil.getConnection();
out.println(conn);
out.println("获取连接成功!");
%>
</body>
</html>
本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。