Linux

mysql with java

newlibra 2023. 4. 7. 23:45
mysql-connector-java-8.0.20.jar
2.28MB

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class ConnectionTest {
    public static void main(String[] args) {
        Connection conn = null;

        try{
            // 1. 드라이버 로딩
            Class.forName("com.mysql.cj.jdbc.Driver");

            // 2. 연결하기
            String url = "jdbc:mysql://127.0.0.1:3306/testdb?serverTimezone=UTC";
            conn = DriverManager.getConnection(url, "testuser", "testuser");
            System.out.println("연결 성공");

        }
        catch(ClassNotFoundException e){
            System.out.println("드라이버 로딩 실패");
        }
        catch(SQLException e){
            System.out.println("에러: " + e);
        }
        finally{
            try{
                if( conn != null && !conn.isClosed()){
                    conn.close();
                }
            }
            catch( SQLException e){
                e.printStackTrace();
            }
        }
    }
}