0. 소개
MySQL과 mm.mysql JDBC 드라이버가 잘 연동된다고 보고된 버전은 다음과 같습니다.
- MySQL 3.23.47, MySQL 3.23.47 using InnoDB, MySQL 4.0.1alpha
- mm.mysql 2.0.14 (JDBC Driver)
새로 MySQL mm.mysql 3.0 driver를 테스트해봤다면 알려주시기 바랍니다. 1. MySQL 설정
달리하면 문제를 일으킬 수도 있으므로 이 지시를 반드시 따르십시오.
test 유저, 새 데이타베이스, 테스트 테이블 하나를 만드십시오. mySQL 유저는 할당된 패스워드가 있어야합니다. 비어있는 패스워드를 가지고서는 드라이버가 연결에 실패할 것입니다.
| | |
| mysql> GRANT ALL PRIVILEGES ON *.* TO javauser@localhost -> IDENTIFIED BY 'javadude' WITH GRANT OPTION;mysql> create database javatest;mysql> use javatest;mysql> create table testdata ( -> id int not null auto_increment primary key, -> foo varchar(25), -> bar int); | |
| | |
주의: 위의 유저는 테스트가 끝나면 제거되어야 합니다.
다음으로 testdata 테이블에 테스트 데이타를 넣으십시오.
| | |
| mysql> insert into testdata values(null, 'hello', 12345);Query OK, 1 row affected (0.00 sec)mysql> select * from testdata;+----+-------+-------+| ID | FOO | BAR |+----+-------+-------+| 1 | hello | 12345 |+----+-------+-------+1 row in set (0.00 sec)mysql> | |
| | |
2. server.xml 설정
$CATALINA_HOME/conf/server.xml
에 리소스 선언을 추가하여 Tomcat에서의 JNDI 데이타소스를 설정하십시오.
이것을 examples 컨텍스트의 </Context>
와 localhost 정의를 닫는 태그인 </Host>
사이에 추가하십시오.
| | |
| <Context path="/DBTest" docBase="DBTest" debug="5" reloadable="true" crossContext="true"> <Logger className="org.apache.catalina.logger.FileLogger" prefix="localhost_DBTest_log." suffix=".txt" timestamp="true"/> <Resource name="jdbc/TestDB" auth="Container" type="javax.sql.DataSource"/> <ResourceParams name="jdbc/TestDB"> <parameter> <name>factory</name> <value>org.apache.commons.dbcp.BasicDataSourceFactory</value> </parameter> <!-- Maximum number of dB connections in pool. Make sure you configure your mysqld max_connections large enough to handle all of your db connections. Set to 0 for no limit. --> <parameter> <name>maxActive</name> <value>100</value> </parameter> <!-- Maximum number of idle dB connections to retain in pool. Set to 0 for no limit. --> <parameter> <name>maxIdle</name> <value>30</value> </parameter> <!-- Maximum time to wait for a dB connection to become available in ms, in this example 10 seconds. An Exception is thrown if this timeout is exceeded. Set to -1 to wait indefinitely. --> <parameter> <name>maxWait</name> <value>10000</value> </parameter> <!-- MySQL dB username and password for dB connections --> <parameter> <name>username</name> <value>javauser</value> </parameter> <parameter> <name>password</name> <value>javadude</value> </parameter> <!-- Class name for mm.mysql JDBC driver --> <parameter> <name>driverClassName</name> <value>org.gjt.mm.mysql.Driver</value> </parameter> <!-- The JDBC connection url for connecting to your MySQL dB. The autoReconnect=true argument to the url makes sure that the mm.mysql JDBC Driver will automatically reconnect if mysqld closed the connection. mysqld by default closes idle connections after 8 hours. --> <parameter> <name>url</name> <value>jdbc:mysql://localhost:3306/javatest?autoReconnect=true</value> </parameter> </ResourceParams></Context> | |
| | |
3. web.xml 설정
이제 테스트 애플리케이션에 대한 WEB-INF/web.xml
을 만드십시오.
| | |
| <?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"><web-app> <description>MySQL Test App</description> <resource-ref> <description>DB Connection</description> <res-ref-name>jdbc/TestDB</res-ref-name> <res-type>javax.sql.DataSource</res-type> <res-auth>Container</res-auth> </resource-ref></web-app> | |
| | |
4. 테스트 코드
이제 이후에 사용할 간단한 test.jsp 파일을 만드십시오.
| | |
| <html> <head> <title>DB Test</title> </head> <body> <% foo.DBTest tst = new foo.DBTest(); tst.init(); %> <h2>Results</h2> Foo <%= tst.getFoo() %><br/> Bar <%= tst.getBar() %> </body></html> | |
| | |
새로 만들어진 데이타소스와 커넥션풀을 실제로 사용할 자바 클래스를 만드십시오. 주의: 이 코드는 실무에서 쓰일 만한 코드는 아닙니다. 단지 테스트 목적으로만 사용되는 것입니다. :-)
| | |
| package foo;import javax.naming.*;import javax.sql.*;import java.sql.*;public class DBTest { String foo = "Not Connected"; int bar = -1; public void init() { try{ Context ctx = new InitialContext(); if(ctx == null ) throw new Exception("Boom - No Context"); DataSource ds = (DataSource)ctx.lookup( "java:comp/env/jdbc/TestDB"); if (ds != null) { Connection conn = ds.getConnection(); if(conn != null) { foo = "Got Connection "+conn.toString(); Statement stmt = conn.createStatement(); ResultSet rst = stmt.executeQuery( "select id, foo, bar from testdata"); if(rst.next()) { foo=rst.getString(2); bar=rst.getInt(3); } conn.close(); } } }catch(Exception e) { e.printStackTrace(); } } public String getFoo() { return foo; } public int getBar() { return bar;}} | |
| | |
마지막으로 웹 애플리케이션을 $CATALINA_HOME/webapps
에 DBTest.war
라는 이름의 war 파일이나 DBTest
라는 서브 디렉토리로 배치하십시오.
배치되고 나면 실제로 실행이 되는지 보기 위해 브라우저에서 http://localhost:8080/DBTest/test.jsp
를 열어보십시오.