• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 219
  • Last Modified:

Convert Existing DB Connection File to Use db.properties file

I have a file I use to establish all of my db connections. I would like to take this file and make it use a db.properties file so I can make changes to the db paramaters without affecting the compiled code.

This is the contents of the db.properties:
#SQL SERVER
drivers=net.sourceforge.jtds.jdbc.Driver
url=jdbc:jtds:sqlserver://localhost:1433/snadis;TDS7.0;
maxconn=900
user=snadis
password=SNADIS

Here is the file I currently use:

public class ConnectionManager {

    //This is the area I desire to change to use the db.properties information
    // True if the database support transactions.
    private static boolean transactionsSupported = true;
    private static String driver = "net.sourceforge.jtds.jdbc.Driver";
    private static String url = "jdbc:jtds:sqlserver://localhost/snadis;TDS=7.0";
    private static String username = "snadis";
    private static String password = "SNADIS";
 
    /**
     * Returns a database connection from the currently active connection
     * provider. (auto commit is set to true).
     */
   
    private void getConnectionstr(){
          
          //Properties  props = new Properties();
          
          if (ConnectionManager.transactionsSupported) {
                transactionsSupported = true;
      
          }else{
                transactionsSupported = false;
          }
          
    }
    public static Connection getConnection() throws Exception {
                 
        Connection tmpCon = null;
        Class driverClass = null;

System.err.println("driver is:" + driver);
System.err.println("url is:" + url);
System.err.println("username is:" + username);
System.err.println("password is:" + password);

        try {
            driverClass = Class.forName(driver);
        } catch (ClassNotFoundException ex) {
            System.err.println("Unable to get class:" + driver);
            throw ex;
        }
       
        try {
            DriverManager.registerDriver((Driver) driverClass.newInstance());
        } catch (Exception sqlex) {
                System.err.println("Unable to register driver " + driver);
                throw sqlex;
            }

        try {
            tmpCon = DriverManager.getConnection(url, username, password);
        } catch (SQLException sqlex) {
            System.err.println("Unable to get connection.");
            throw sqlex;
        }

        return tmpCon;
       
    }

    /**
     * Returns a Connection from the currently active connection provider that
     * is ready to participate in transactions (auto commit is set to false).
     */
    public static Connection getTransactionConnection() throws Exception {
          Connection tmpCon = getConnection();
          
          try {    
       
              if (isTransactionsSupported()) {
                  tmpCon.setAutoCommit(false);
              }
              
          }catch(Exception ex){
                throw ex;
          }

              return tmpCon;
    }

    /**
     * Closes a Connection. However, it first rolls back the transaction or
     * commits it depending on the value of <code>abortTransaction</code>.
     */
    public static void closeTransactionConnection(Connection conn, boolean abortTransaction) {
        // test to see if the connection passed in is null
        if (conn == null) {
            return;
        }
               
        // Rollback or commit the transaction
        if (isTransactionsSupported()) {
            try {
                if (abortTransaction) {
                    conn.rollback();
                }
                else {
                    conn.commit();
                }
            }
            catch (Exception e) {
            System.err.println(e);            
            }
        }
        try {
            // Reset the connection to auto-commit mode.
            if (isTransactionsSupported()) {
                conn.setAutoCommit(true);
            }
        }
        catch (Exception e) { System.err.println(e); }
        try {
            // Close the db connection.
            conn.close();
        }
        catch (Exception e) { System.err.println(e); }

    }

    public static boolean isTransactionsSupported() {
        return transactionsSupported;
    }

    public void setDriver (String inDriver) {
        driver = inDriver;
    }
    public void setDBUrl (String inUrl) {
        url = inUrl;
    }
    public void setDBUser (String inUser) {
        username = inUser;
    }
    public void setDBPassword (String inPassword) {
        password = inPassword;
    }
   
      /**
       *
       */
      public ConnectionManager() {            
            super();      
            getConnectionstr();
      }
}
0
rcmb
Asked:
rcmb
  • 3
1 Solution
 
zzynxSoftware engineerCommented:
That's rather straightforward:

Reading and Writing a Properties File: http://javaalmanac.com/egs/java.util/Props.html
Getting and Setting Properties: http://javaalmanac.com/egs/java.util/GetSetProps.html?l=rel
0
 
zzynxSoftware engineerCommented:
So,

    Properties properties = new Properties();
    try {
        properties.load(new FileInputStream("db.properties"));
    } catch (IOException e) {
    }

    then

    properties.getProperty("url") will give you "jdbc:jtds:sqlserver://localhost:1433/snadis;TDS7.0"
and
    properties.getProperty("drivers") will give you "net.sourceforge.jtds.jdbc.Driver"    // didn't you mean driver=...
and so on
0
 
aozarovCommented:
Uzing zzynx advice you can have the properties having defaults (for ones that may not be provided).
Properties defaults = new Properties();
defaults.setProperty("driver", "net.sourceforge.jtds.jdbc.Driver")
... // add more to defaults

then create properties using this way:
Properties properties = new Properties(defaults);
...

Any property defined in your db.properties will override the default.
you can also get a default value is not provided using propertites.getProperty("driver",  "net.sourceforge.jtds.jdbc.Driver") [second argument is default] but the above
aproach should be cleaner.
0
 
zzynxSoftware engineerCommented:
Thanks for accepting
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: Microsoft Azure 2017

Azure has a changed a lot since it was originally introduce by adding new services and features. Do you know everything you need to about Azure? This course will teach you about the Azure App Service, monitoring and application insights, DevOps, and Team Services.

  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now