LoginSignup
3
6

More than 3 years have passed since last update.

【Java】MySQLに接続する

Last updated at Posted at 2019-10-21

概要

MySQL : 5.7
Java : 8.1
Mac
Eclipse

始める前に以下条件をクリアしている

・MySQLで既にtableなどができている。
・ターミナルなどで難なく接続できている

JDBCをダウンロード

MySQLのJDBCをダウンロード
https://dev.mysql.com/downloads/connector/j/

「Platform Independent (Architecture Independent), Compressed TAR Archive」 をダウンロード
スクリーンショット 2019-10-21 17.25.07.png

解凍したファイルにmysql-connector-java-5.1.48-bin.jarがあるから、
Tomcatの/Tomcat/libに入れる
(私の場合、/Users/namari/apache-tomcat-9.0.27/lib

接続してみる

プロジェクトの中に、SqlTest.javaを適当に作ってみる。

SqlTest.java
package chapter14;

import java.io.*;
import java.sql.*;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;

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


    protected void doGet(
        HttpServletRequest request,
        HttpServletResponse response
    ) throws ServletException, IOException {

        // 今回は、localhostにあるbook のデータベース
        String url = "jdbc:mysql://localhost/book";

        try{
            Class.forName("com.mysql.jdbc.Driver");
            Connection conn = DriverManager.getConnection(url, "ユーザー名", "パスワード");

            // データベースに対する処理
            msg = "ok";
        } catch (SQLException | ClassNotFoundException e){
            msg = "NG";

        }
        response.getWriter().println(msg);
    }

}
3
6
0

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
3
6