본문 바로가기
Web(국비)/DB연결

DB연결

by Xion 2019. 10. 25.

DBConn.java

package com.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DBConn
{
   private static Connection dbConn;
   
   public static Connection getConnection() throws ClassNotFoundException, SQLException
   {
      if (dbConn == null)
      {
         String url = "jdbc:oracle:thin:@localhost:1521:xe";
         String user = "scott";
         String pwd = "tiger";
         Class.forName("oracle.jdbc.driver.OracleDriver");
         dbConn = DriverManager.getConnection(url, user, pwd);
      }
      return dbConn;
   }
   
   public static Connection getConnection(String url, String user, String pwd) throws ClassNotFoundException, SQLException
   {
      if (dbConn == null)
      {
         Class.forName("oracle.jdbc.driver.OracleDriver");
         dbConn = DriverManager.getConnection(url, user, pwd);
      }
      return dbConn;
   }
   
   public static void close() throws SQLException
   {
      if (dbConn != null)
      {
         if(!dbConn.isClosed())
            dbConn.close();
      }
      dbConn = null;
   }
}

Test001.jsp

<%@page import="java.sql.Connection"%>
<%@page import="com.util.DBConn"%>
<%@ page contentType="text/html; charset=UTF-8"%>
<%

	String str="";

	try
	{
		//getConnection은 Connection type반환
		Connection conn = DBConn.getConnection();
		if(conn!=null)
			str+="데이터베이스 연결 성공~~~";
		
	}catch(Exception e)
	{
		System.out.print(e.toString());
	
	}

%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<div>
		<h1>데이터베이스 연결 실습</h1>
		<hr>
	</div>
	
	<div>
		<h1><%=str %></h1>
	
	</div>
	
</body>
</html>

'Web(국비) > DB연결' 카테고리의 다른 글

DB연결-WebApp09  (0) 2019.10.28
DB-연결 WebApp08  (0) 2019.10.28
[Java] score DB연결  (0) 2019.10.28
DB연결1  (0) 2019.10.27
DB연결2  (0) 2019.10.25