问题
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);}
}
}
回答1:
You can use Properties and read the values from a .properties file.
回答2:
Maybe this helps. It's an example of such config files.
回答3:
InputStream inputStream = null;
Properties properties = new Properties();
try {
inputStream = JDBCDemo.class.getClassLoader().getResourceAsStream("jdbc.properties");
properties.load(inputStream);
}
finally {
try {
if (inputStream != null) {
inputStream.close();
}
}
catch (IOException e) {
;//ignore
}
}
String username = properties.get("username");
回答4:
XML and JSON are structured formats so they needs to be parsed.
Text file will be the simplest to implement but because it is unstructured the end user is going to need going to need to know the internal format understood by your program. For instance an extra space may break your program.
回答5:
Ever think of using spring injection where u can create one config file containing all hardcoded variables which through getters and setters can be put into your code. Then in the future if any of these variables need changing you only change 1 file http://www.springsource.org/javaconfig/
回答6:
generally the uer-id & passwords (rather any resource that needs to be configured from outside your JAR/WAR) is stored in a Properties file as a key value pair. You can then access them using ResourceBundle class : http://docs.oracle.com/javase/1.4.2/docs/api/java/util/ResourceBundle.html
回答7:
For sql
queries you could use a database function
or procedure
which returns some kind of cursor similar to SYS_REFCURSOR
in Oracle
and call the function
or procedure
from front end. By doing this you could avoid hard coding of sql queries in java code.
Regards
来源:https://stackoverflow.com/questions/11634379/username-password-etc-hardcoded-into-program-how-to-pick-them-up-from-a-file