天天看点

java 连接mysql mariadb,如何使用java获取MariaDB连接?

java 连接mysql 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;

}

}

解决方案

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");

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

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