[간단한 게시판 만들기] - 1. DB연동
웹/백엔드, Spring

[간단한 게시판 만들기] - 1. DB연동

 

1. context.xml설정

2. connection설정

3. jdbc사용해서 간단한 select문 만들기

 

tomcat.apache.org/tomcat-9.0-doc/jndi-datasource-examples-howto.html

 

Apache Tomcat 9 (9.0.39) - JNDI Datasource How-To

JNDI Datasource configuration is covered extensively in the JNDI-Resources-HOWTO. However, feedback from tomcat-user has shown that specifics for individual configurations can be rather tricky. Here then are some example configurations that have been poste

tomcat.apache.org

API를 잘 확인하면 모두 나와있는걸 알 수있다.

 

1. context.xml코드

<?xml version="1.0" encoding="UTF-8"?>
<Context>
  <Resource name="jdbc/toy"
            auth="Container"
            type="javax.sql.DataSource"
            username="id"
            password="pd"
            driverClassName="com.mysql.cj.jdbc.Driver"
            url="jdbc:mysql://localhost:3306/디비이름?serverTimezone=UTC&amp;useUniCode=yes&amp;characterEncoding=UTF-8"
            maxTotal="8"
            maxIdle="4"/>
</Context>

 

2. DBUtil.java

static으로 선언해서 Service에서 바로 불러들일 수 있도록 해야한다.

package com.web.toy.DBUtill;

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

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;

public class DBUtil {
	public static Connection getConnection() throws SQLException{
		DataSource ds = null;
		try {
			Context initContext = new InitialContext();
			Context envContext  = (Context)initContext.lookup("java:/comp/env");
			ds = (DataSource)envContext.lookup("jdbc/toy");
		}catch (Exception e) {
			e.printStackTrace();
		}
		return ds.getConnection();
	}
	
	public static void close(AutoCloseable c) {
		if (c != null) {
			try {
				c.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}

 

3. sql문 사용

이것도 위 링크의 API만 확인하면 잘 나와있는걸 알 수 있다. 

	String act = request.getParameter("act");
		System.out.println(act);
		if("login".equals(act)) {
			System.out.println("로그인");
			  PreparedStatement ps = null;
			  ResultSet rs = null;
			  try {
			    String sql = "select userid from ssafy_member;";
			    ps = DBUtil.getConnection().prepareStatement(sql);
			    rs = ps.executeQuery();
			    while(rs.next()){
			    	System.out.println(rs.getString("userid"));
			    }
			  }finally {
				DBUtil.close(rs);
				DBUtil.close(ps);
			}
		}

 

연동이 잘 됨을 확인!!