Help us understand the problem. What is going on with this article?

【Java】MySQLに接続する

概要

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);
    }

}
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした