How to connect MySQL Database in Java using Maven Dependency

Cách kết nối cơ sở dữ liệu MySQL trong Java bằng cách sử dụng phụ thuộc Maven

Để kết nối Java với MySQL ta làm như sau:

Trong file pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>org.fpt</groupId>
<artifactId>javadocfast</artifactId>
<version>1.0</version>

<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.21</version>
</dependency>
</dependencies>
</project>

Tạo file DBConnection.java
package com.fpt.common;

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

public class DBConnection {

private static final String URL = "jdbc:mysql://localhost:3306/javadocfast";
private static final String USER = "root";
private static final String PASSWORD = "";

public static Connection getConnect() {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
return DriverManager.getConnection(URL, USER, PASSWORD);
} catch (Exception e) {
System.out.println(e.getMessage());
return null;
}
}

public static void main(String[] args) {
Connection connection = DBConnection.getConnect();
try {
if(connection != null && !connection.isClosed()) {
System.out.println("Yes");
} else {
System.out.println("No");
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}

}

Để test có kết nối thành công hay không, chạy file DBConnection.java nếu trả về Yes là thành công

Nhận xét

Bài đăng phổ biến từ blog này

Java EE Web Application (JSP/Servlet, EJB, JPA, SQL Server, Glassfish) Full Tutorial

Build validation using VanillaJS for Form Submit

Java EE Web Application (JavaServer Faces, EJB, JPA, SQL Server, Glassfish) Full Tutorial