如何使用 java 获得 MariaDB 连接?

2022-01-15 00:00:00 mariadb database-connection java

我在 mysql 服务器上工作并成功连接了我的 java 应用程序.现在我改用 MariaDB.如何使用 java 连接 MariaDB 服务器?这应该如何改变?

I worked on mysql server and connected my java applications successfully. And now I changed to MariaDB. How to connect with MariaDB server using java? How this should be changed?

public class DBConnection {

private Connection connection;
private static DBConnection dBConnection;

public DBConnection() throws ClassNotFoundException, SQLException {
    Class.forName("com.mysql.jdbc.Driver");
    connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/db", "root", "mysql");
}

public static DBConnection getDBConnection() throws ClassNotFoundException, SQLException {
    if (dBConnection == null) {
        dBConnection = new DBConnection();
    }
    return dBConnection;
}

public Connection getConnection() {
    return connection;
}

}

推荐答案

MariaDB 的小改动如下: 将 MariaDB Connector/J 与以下 Driver 类一起使用:

Minor changes for MariaDB are as follows: Use the MariaDB Connector/J with the following Driver class:

org.mariadb.jdbc.Driver

对于数据库连接,请使用以下结构:

For DB Connection use the following structure:

jdbc:(mysql|mariadb)://host:port/[database]

因此,您上面的代码只需要更改

Therefore, your code as above would only require the change for

Class.forName("org.mariadb.jdbc.Driver");

因为 MySQL 和 MariaDB 客户端是兼容的,所以其余的都可以正常工作.毕竟,MariaDB 是 MySQL 的增强型、插入式替代品.

and the rest would work well since MySQL and MariaDB clients are compatible.After all, MariaDB is an enhanced, drop-in replacement for MySQL.

有关使用 Java 连接器连接到 MariaDB 的更多信息,请访问 MariaDB 知识库(MariaDB 连接器/J

More information about connecting to MariaDB using the Java Connector can be accessed from MariaDB Knowledge Base (MariaDB Connector/J

相关文章