概要
JavaからMySQLを操作したい時のメモ。
JavaからMySQLへの接続をシンプルなサンプルでメモする。
- Tomcat 7
- Java 7
- MySQL 5.6
server.xml
Tomcat7の設定ファイルにContextを追加する。
DBConnect:プロジェクト名
username:MySQLへのログインユーザーID
password:MySQLへのログインユーザーパスワード
url:ローカルホストにインストールしたMySQL
<Context docBase="DBconnect"
path="/DBconnect"
reloadable="true"
source="org.eclipse.jst.jee.server:DBconnect">
<Resource
auth="Container"
driverClassName="com.mysql.jdbc.Driver"
name="jdbc/selfjsp"
username="root"
password="root"
type="javax.sql.DataSource"
url="jdbc:mysql://localhost/selfjsp" />
</Context>
web.xml
「res-ref-name」はserver.xmlのnameと合わせるよう注意。
<?xml version="1.0" encoding="UTF-8"?>
<web-app
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>DBconnect</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<resource-ref>
<res-ref-name>jdbc/selfjsp</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
</web-app>
JSP
<%@ page contentType="text/html;charset=UTF-8" import="java.sql.*, javax .naming.*, javax.sql.*" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>データベースへの接続</title>
</head>
<body>
<%
Context context = new InitialContext();
DataSource ds = (DataSource)context.lookup("java:comp/env/jdbc/selfjsp") ;
Connection db = ds.getConnection();
db.close();
%>
データベースへの接続に成功しました。
</body>
</html>