SeregPie
SeregPie

Reputation: 1253

Create DataSource from JDBC URL

It can be handy to pass the path, username, password and all the options in a single string to create a connection to a database. Is there a way to create a DataSource object from a single URL? Maybe it is possible to create a DataSource from an open SQL connection?

String url = "jdbc:mysql://localhost:3306/db?user=root&password=123&autoReconnect=true&useSSL=false&allowMultiQueries=true";
Connection conn = DriverManager.getConnection(url);

Upvotes: 2

Views: 3528

Answers (1)

Gord Thompson
Gord Thompson

Reputation: 123849

Is there a way to create a DataSource object from a single URL?

For what it's worth, this seems to work for MySQL Connector/J:

String connectionUrl = "jdbc:mysql://localhost:3307/mydb";

com.mysql.jdbc.jdbc2.optional.MysqlDataSource mds =
        new com.mysql.jdbc.jdbc2.optional.MysqlDataSource();
mds.setUrl(connectionUrl);

Maybe it is possible to create a DataSource from an open SQL connection?

Maybe it is. You could try retrieving the connection URL via

conn.getMetaData().getURL()

and proceed as above.

Upvotes: 4

Related Questions