1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Java 】サーブレット(tomcat)&MySQL&Java でコネクションプールを使用して接続してみた

Last updated at Posted at 2019-10-24

関連記事

【Java】JDBCをインストールして、servlet + MySQL で接続してみた。( DAO / Bean を使用バージョンあり)

参考サイト

※ めちゃくちゃ参考になった!!!
Java で MySQL に 接続する 方法

JDBC ドライバ導入

  1. 公式サイトからmysql-connector-java-8.0.18.zipダウンロード
  2. 解凍するしてmysql-connector-java-5.1.48-bin.jarを取り出す
  3. /WebContent/WEB-INF/lib/mysql-connector-java-5.1.48-bin.jarに入れる

context.xml を作成する

/WebContent/META-INF/context.xmlに作成する

context.xml
<?xml version="1.0" encoding="UTF-8" ?>
<Context>
	<Resource name = "jdbc/book"
              auth = "Container"
              type = "javax.sql.DataSource"
              driverClassName = "com.mysql.jdbc.Driver"
              url      = "jdbc:mysql://localhost/book"
              username = "namari"
              password = "password">
	</Resource>
</Context>

サーブレット

/Sample/webapps/book/WEB-INF/src/chapter14/All.javaに作成する

All.java
package chapter14;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;

import javax.naming.InitialContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.*;

/**
 * Servlet implementation class All
 */
@WebServlet("/All")
public class All extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public All() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		PrintWriter out = response.getWriter();

		try {
			// コネクション取得
			InitialContext ic = new InitialContext();
			DataSource ds = (DataSource) ic.lookup("java:/comp/env/jdbc/book");
			Connection con = ds.getConnection();

			// SQL文送信
			PreparedStatement st = con.prepareStatement("select * from product");
			// 実行&結果受け取り
			ResultSet rs = st.executeQuery();

			// データの表示
			while (rs.next()) {
				out.println(rs.getInt("id") + ":" + rs.getString("name") + ":" + rs.getInt("price"));
			}

			// データベース切断
			st.close();
			con.close();

		} catch (Exception e) {
			// 接続・SQL文エラー
			e.printStackTrace(out);

		} // try
	}

}
1
2
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?