EclipseMySQLJDBC_Properties1
  • Objects :
    Connection c = null; Statement st = null;
    Properties param = new Properties();
  • Connect DB : One string connects db with users name and pwd
    c = DriverManager
    .getConnection("jdbc:postgresql://localhost:5432/postgres",
    "postgres", "postgre_manas9");
    OR
    c = DriverManager.getConnection("jdbc:mysql://localhost:5432/test?","Manas9", "Manas9237");
  •  Properties: user and pwd are tendered by variables/literals
    param.put("user",user); param.put("password",pwd);
    c = DriverManager.getConnection(dbURL,param);
    To avoid hard coding all the database parameters in the code, you can use a Java properties file to store them. In case of changes, you just need to change them in the properties file and you don’t have to recompile the code.
Snapshots;

Try and catch block:

Code :

package manas.com;
import java.io.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.Properties;
public class JavaTemplate1 {

public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Hello world");
Connection c = null; Statement st = null;
Properties param = new Properties();
//postgresql
//String dbURL = "jdbc:postgresql://localhost:5432/postgres";
//String user = "postgres"; String pwd = "postgre_manas9";
//mysql
String dbURL = "jdbc:mysql://localhost/test?";
String user = "Manas9"; String pwd = "Manas9237";

// connecting to db
try {
//replacing Class.forName("org.postgresql.Driver");
param.put("user",user); param.put("password",pwd);
c = DriverManager.getConnection(dbURL, param);
System.out.println("Parameter processed");

} catch (SQLException ex) { ex.getErrorCode();
String message = ex.getMessage();
System.out.println(message);
} finally {
System.out.println("going through final block");
try {
if (st== null || st.isClosed()) {
System.out.println("closing statement");
} else {
st.close();
}
if (c != null && !c.isClosed()) {
c.close();
System.out.println("closing connection");
}
} catch (SQLException ex) { ex.getErrorCode();
ex.getMessage();
}
}


//System.out.println("Connected to database successfully");
}
}
 

Output: