How to connect MySQL database in Java EE?
You can use the JDBC (Java Database Connectivity) technology in Java programs to connect to a MySQL database. First, make sure you have installed the MySQL database and added the MySQL driver (JDBC driver) to your Java project. You can then use the following code example to connect to the MySQL database:
import java.sql.Connection;import java.sql.DriverManager;
import java.sql.SQLException;
public class MySQLConnection {
public static void main(String[] args) {
// 数据库连接信息
String url = "jdbc:mysql://localhost:3306/mydatabase";
String username = "root";
String password = "password";
// 创建数据库连接
try {
Connection conn = DriverManager.getConnection(url, username, password);
System.out.println("成功连接到MySQL数据库!");
// 在这里可以执行数据库操作
// 关闭数据库连接
conn.close();
} catch (SQLException e) {
System.out.println("连接MySQL数据库失败!");
e.printStackTrace();
}
}
}
In the code above, the url variable specifies the URL of the MySQL database to connect to, while the username and password variables respectively specify the username and password of the database. Once successfully connected to the MySQL database, database operations can be executed in the connecting code block. Lastly, remember to close the database connection after the program ends to release resources.
This is just a simple example code that you can modify and expand according to your own needs.