레이블이 jdbc 설정인 게시물을 표시합니다. 모든 게시물 표시
레이블이 jdbc 설정인 게시물을 표시합니다. 모든 게시물 표시

2012-10-31

java] jsp jdbc 연결 예제




출처  : http://allinfo.tistory.com/14


파일명 : jdbctest.jsp

<%@ page contentType="text/html;charset=euc-kr" import="java.sql.*" %>
<% request.setCharacterEncoding("euc-kr"); %>
<%
 // 데이터베이스 연결관련 변수 선언
 Connection conn = null;
 Statement stmt = null;
 // 데이터베이스 연결관련정보를 문자열로 선언
 String jdbc_driver = "oracle.jdbc.driver.OracleDriver";
 String jdbc_url = "jdbc:oracle:thin:@localhost:1521:ORCL";

 try{
  // JDBC 드라이버 로드
  Class.forName(jdbc_driver);
  // 데이터베이스 연결정보를 이용해 Connection 인스턴스 확보
  conn = DriverManager.getConnection(jdbc_url,"scott","tiger");
  // Connection 클래스의 인스턴스로 부터 SQL  문 작성을 위한 Statement 준비
  stmt = conn.createStatement();
  // username 값을 입력한 경우 sql 문장을 수행.
if(request.getParameter("username") != null) {
   String sql = "insert into jdbc_test values('"+request.getParameter("username")+"','"+request.getParameter("email")+"')";
   stmt.executeUpdate(sql);
  }
 }
 catch(Exception e) {
  System.out.println(e);
 }
%>
<HTML>
<HEAD><TITLE>JDBC 테스트 </TITLE></HEAD>
<BODY>
<center>
<H2>이벤트 등록</H2>
<HR>
<form name=form1 method=post action=jdbctest.jsp>
등록이름 : <input type=text name=username>
email주소 : <input type=text name=email size=20>
<input type=submit value="등록">
</form>
<HR>
</center>
# 등록 목록<P>
<%
 try{
  // select 문장을 문자열 형태로 구성한다.  String sql = "select username, email from jdbc_test";
  // select 를 수행하면 데이터정보가 ResultSet 클래스의 인스턴스로 리턴됨.  ResultSet rs = stmt.executeQuery(sql);
  int i=1;
  // 마지막 데이터까지 반복함.  while(rs.next()) {
   out.println(i+" : "+rs.getString(1)+" , "+rs.getString("email")+"<BR>");
   i++;
  }
  // 사용한 자원의 반납.
  rs.close();
  stmt.close();
  conn.close();
 }
 catch(Exception e) {
  System.out.println(e);
 }
%>
</BODY>
</HTML>

Java] Ibatis 다중링크 사용



출처 : http://mimul.com/pebble/default/2008/02/24/1203779580000.html



웹 어플리케이션에서 하나 이상의 데이터 베이스에 접근하여 어플리케이션이 실행되는 환경들이 많을 것입니다.
iBatis에서 어떻게 활용되는 지 사용방법을 공유합니다.
사용환경은 iBatis와 DBCP입니다.
  1. database.properties

    driver=oracle.jdbc.driver.OracleDriver
    jdbc.url1=jdbc:oracle:thin:@mimuluserdb:1521:mimuluser
    username1=mimuluser
    password1=mimuluser

    jdbc.url2=jdbc:oracle:thin:@pepsiuserdb:1521:pepsiuser
    username2=pepsiuser
    password2=pepsiuser
  2. sqlmap1.xml 
    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE sqlMapConfig
            PUBLIC "-//iBATIS.com//DTD SQL Map Config 2.0//EN"
            "http://www.ibatis.com/dtd/sql-map-config-2.dtd">
    <sqlMapConfig>
        <properties resource="com/mimul/dwr/app/
                   resource/database.properties"/>
        <settings
                cacheModelsEnabled="true"
                enhancementEnabled="true"
                lazyLoadingEnabled="true"
                maxRequests="40"
                maxSessions="20"
                maxTransactions="5"
                useStatementNamespaces="false"
                />
        <transactionManager type="JDBC">
            <dataSource type="DBCP">
                <property name="driverClassName" value="${driver}"/>
                <property name="url" value="${jdbc.url1}"/>
                <property name="username" value="${username1}"/>
                <property name="password" value="${password1}"/>

                <!-- OPTIONAL PROPERTIES BELOW -->
                <property name="initialSize" value="5"/>
                <property name="maxActive" value="30"/>
                <property name="maxIdle" value="20"/>
                <property name="maxWait" value="60000"/>
                <property name="poolPreparedStatements" value="true"/>
                <property name="validationQuery" value="select 0 from dual"/>
                <property name="testOnBorrow" value="true"/>
                <property name="maximumActiveConnections" value="10"/>
                <property name="maximumIdleConnections" value="5"/>
                <property name="maximumWait" value="60000"/>
                <property name="logAbandoned" value="false"/>
                <property name="removeAbandoned" value="false"/>
                <property name="removeAbandonedTimeout" value="50000"/>
            </dataSource>
        </transactionManager>
        <sqlMap resource="com/mimul/dwr/app/sql/Mimul.xml"/>
    </sqlMapConfig>
  3. sqlmap2.xml
    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE sqlMapConfig
            PUBLIC "-//iBATIS.com//DTD SQL Map Config 2.0//EN"
            "http://www.ibatis.com/dtd/sql-map-config-2.dtd">
    <sqlMapConfig>
        <properties resource="com/mimul/dwr/app/resource/database.properties"/>
        <settings
                cacheModelsEnabled="true"
                enhancementEnabled="true"
                lazyLoadingEnabled="true"
                maxRequests="40"
                maxSessions="20"
                maxTransactions="5"
                useStatementNamespaces="false"
                />
        <transactionManager type="JDBC">
            <dataSource type="DBCP">
                <property name="driverClassName" value="${driver}"/>
                <property name="url" value="${jdbc.url2}"/>
                <property name="username" value="${username2}"/>
                <property name="password" value="${password2}"/>

                <!-- OPTIONAL PROPERTIES BELOW -->
                <property name="initialSize" value="5"/>
                <property name="maxActive" value="30"/>
                <property name="maxIdle" value="20"/>
                <property name="maxWait" value="60000"/>
                <property name="poolPreparedStatements" value="true"/>
                <property name="validationQuery" value="select 0 from dual"/>
                <property name="testOnBorrow" value="true"/>
                <property name="maximumActiveConnections" value="10"/>
                <property name="maximumIdleConnections" value="5"/>
                <property name="maximumWait" value="60000"/>
                <property name="logAbandoned" value="false"/>
                <property name="removeAbandoned" value="false"/>
                <property name="removeAbandonedTimeout" value="50000"/>
            </dataSource>
        </transactionManager>
        <sqlMap resource="com/mimul/dwr/app/sql/Pepsi.xml"/>
    </sqlMapConfig>
  4. SqlConfig.java
    import java.io.File;
    import java.io.Reader;

    import com.ibatis.common.resources.Resources;
    import com.ibatis.sqlmap.client.SqlMapClient;
    import com.ibatis.sqlmap.client.SqlMapClientBuilder;
    import com.jaeminara.common.log.LogPool;

    public class SqlConfig {
        private static SqlMapClient sqlMap1 = null;
        private static SqlMapClient sqlMap2 = null;
        private static SqlConfig instance_ = null;
      
        private SqlConfig() throws Exception
        {
            Reader reader = null;
            String resource = null;
            try {
                if (sqlMap == null) {
                    resource = "sqlmap1.xml";
                     reader = Resources.getResourceAsReader(resource);
                     sqlMap1 = SqlMapClientBuilder.buildSqlMapClient(reader);
                    resource = "sqlmap2.xml";
                     reader = Resources.getResourceAsReader(resource);
                     sqlMap2 = SqlMapClientBuilder.buildSqlMapClient(reader);
                     reader.close();
                }
            } catch (Exception e) {
                System.out.println(e);
                throw e;
            } finally {
                if (reader != null)
                    reader.close();
                reader = null;
                rsc = null;
            }
        }
      
        public static SqlConfig instance()
        {
            try {
                if (instance_ == null) {
                    synchronized (SqlConfig.class) {
                        if (instance_ == null)
                            instance_ = new SqlConfig();
                    }
                }
            } catch (Exception e) {
                System.out.println(e);
            }
            return instance_;
        }

        /**
         * Return SqlMapClient for SDP schema
         *
         * @return
         */
        public static SqlMapClient getSqlMap1Instance()
        {
            return sqlMap1;
        }

        /**
         * Return SqlMapClient for SDP schema
         *
         * @return
         */
        public static SqlMapClient getSqlMap2Instance()
        {
            return sqlMap2;
        }
    }