How to establish a connection between Java and a database
To establish a connection with a database, you can use Java’s JDBC (Java Database Connectivity) technology. Below is a simple example code that demonstrates how to use Java’s JDBC to connect with a database.
import java.sql.Connection;import java.sql.DriverManager;
import java.sql.SQLException;
public class DatabaseConnection {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/mydatabase"; // 数据库连接URL
String username = "username"; // 数据库用户名
String password = "password"; // 数据库密码
try {
// 加载数据库驱动
Class.forName("com.mysql.cj.jdbc.Driver");
// 建立数据库连接
Connection conn = DriverManager.getConnection(url, username, password);
// 连接成功,可以进行数据库操作
// 关闭连接
conn.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
In the example code above, it is necessary to first load the database driver and then establish a database connection using the `DriverManager.getConnection()` method. The `url` parameter represents the database connection URL, while `username` and `password` are the database’s login credentials. Please modify the database connection parameters in the example code according to your specific situation.