Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
6
Help us understand the problem. What is going on with this article?
@namari

【Java】MySQLに接続する

More than 1 year has passed since last update.

概要

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

}
6
Help us understand the problem. What is going on with this article?
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
namari
プログラマーとしてぴよこです。でも頑張ります。

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
6
Help us understand the problem. What is going on with this article?