?
Solved

Convert Existing DB Connection File to Use db.properties file

Posted on 2005-04-27
4
Medium Priority
?
208 Views
Last Modified: 2010-03-31
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
Comment
Question by:rcmb
  • 3
4 Comments
 
LVL 37

Expert Comment

by:zzynx
ID: 13875800
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
 
LVL 37

Accepted Solution

by:
zzynx earned 2000 total points
ID: 13875836
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
 
LVL 15

Expert Comment

by:aozarov
ID: 13876447
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
 
LVL 37

Expert Comment

by:zzynx
ID: 13924343
Thanks for accepting
0

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
The viewer will learn how to implement Singleton Design Pattern in Java.
Suggested Courses
Course of the Month14 days, 19 hours left to enroll

840 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question