In the following code snippet you’ll 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 = "root";
private static final String PASSWORD = "";
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 products");
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
<!-- https://search.maven.org/remotecontent?filepath=mysql/mysql-connector-java/8.0.31/mysql-connector-java-8.0.31.jar -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.31</version>
</dependency>
Latest posts by Wayan (see all)
- How do I calculate days between two dates excluding weekends and holidays? - January 12, 2023
- How do I discover the quarter of a given date? - January 11, 2023
- How do I export MySQL database schema into markdown format? - January 10, 2023