In the following code snippet, you will see how to pass some connection arguments when connecting to a database. To do this, we can use the java.util.Properties
class. We can put some key value pairs as a connection arguments to the Properties
object
before we pass this information into the DriverManager
class.
Let’s see the example below:
package org.kodejava.jdbc;
import java.sql.*;
import java.util.Properties;
public class GetConnectionWithProperties {
private static final String URL = "jdbc:mysql://localhost/kodejava";
private static final String USERNAME = "kodejava";
private static final String PASSWORD = "s3cr*t";
public static void main(String[] args) {
GetConnectionWithProperties demo = new GetConnectionWithProperties();
try (Connection connection = demo.getConnection()) {
// do something with the connection.
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM product");
while (rs.next()) {
System.out.println("Code = " + rs.getString("code"));
System.out.println("Name = " + rs.getString("name"));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
private Connection getConnection() throws SQLException {
Properties connectionProps = new Properties();
connectionProps.put("user", USERNAME);
connectionProps.put("password", PASSWORD);
Connection connection = DriverManager.getConnection(URL, connectionProps);
System.out.println("Connected to database.");
return connection;
}
}
Maven Dependencies
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.4.0</version>
</dependency>