Java连接MySQL远程数据库是指在Java应用程序中通过网络连接到位于远程服务器上的MySQL数据库,以执行数据查询、更新等操作。
pom.xml
(如果使用Maven)中添加以下依赖:<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.26</version>
</dependency>
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class MySQLConnectionTest {
public static void main(String[] args) {
String url = "jdbc:mysql://your_remote_mysql_host:3306/your_database_name";
String user = "your_username";
String password = "your_password";
try (Connection conn = DriverManager.getConnection(url, user, password)) {
System.out.println("Connected to the remote MySQL database!");
} catch (SQLException e) {
System.err.println("Failed to connect to the remote MySQL database.");
e.printStackTrace();
}
}
}
wait_timeout
和interactive_timeout
设置合理。GRANT ALL PRIVILEGES ON your_database_name.* TO 'your_username'@'%' IDENTIFIED BY 'your_password';
FLUSH PRIVILEGES;
请注意,在实际应用中,还需要考虑数据库连接池、异常处理、安全性等更多方面。
领取专属 10元无门槛券
手把手带您无忧上云