Search code examples
javamysqleclipsejdbcconfiguration-files

username, password etc hardcoded into program - how to pick them up from a file instead?


I have made some code in ECLIPSE. As you can see, the username, password, database URL, SQL Queries are hardcoded into my program. I don't want to change my code and recompile it every time I change the password, username of my database or modify the query. For that reason, I want to put these "parameters" inside a file (text, XML, json ???). I want to be able to change the parameters easily. So what should I do ? What kind of file should I use ? I want to avoid XML, json because you need to know both well. XML and JSON can be difficult when the code grows big.

import java.sql.*;

public class JDBCDemo {


static String query = 
        "SELECT customerno, name " +
        "FROM customers;";


public static void main(String[]args)
{
    String username = "cowboy";
    String password = "123456";
    try
    {
        Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/business", username, password);
        Statement stmt = con.createStatement();
        ResultSet rs = stmt.executeQuery(query);
    }catch(SQLException ex){System.out.println("Exception! " + ex);}

}

}

Solution

  • You can use Properties and read the values from a .properties file.