连接MySQL数据库的URL格式通常如下:
jdbc:mysql://[hostname]:[port]/[database]?[parameters][hostname]:数据库服务器的主机名或IP地址。如果是本地数据库,可以使用localhost或127.0.0.1。[port]:MySQL服务运行的端口号,默认是3306。[database]:要连接的数据库名称。[parameters]:连接参数,如字符集设置characterEncoding=UTF-8,时区设置serverTimezone=UTC等。例如,如果你的MySQL数据库运行在本地(localhost),默认端口(3306),数据库名为mydb,并且你想设置字符集为UTF-8,那么连接URL将是:
jdbc:mysql://localhost:3306/mydb?characterEncoding=UTF-8&serverTimezone=UTC优势:
类型:
应用场景:
可能遇到的问题及解决方法:
示例代码(Java):
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://localhost:3306/mydb?characterEncoding=UTF-8&serverTimezone=UTC";
String user = "yourUsername";
String password = "yourPassword";
try (Connection conn = DriverManager.getConnection(url, user, password)) {
System.out.println("Connected to the database!");
} catch (SQLException e) {
System.out.println("Connection failed!");
e.printStackTrace();
}
}
}确保在运行上述代码之前,已经在项目中添加了MySQL JDBC驱动程序的依赖,并且已经正确配置了数据库服务器。
参考链接:
没有搜到相关的文章