Read the connection string from the Operation profile properties, which is a data connection that requires three files to be written, two of which are Java classes, and one is a file with a suffix named. Properties, which is placed in the SRC working directory.
A file suffix of. Properties is named Dbconfig.properties here, with the following code:
Url=jdbc:mysql://localhost:3306/test
User=root
Pwd=root
This connection is the way the Sqlservcer database is connected, and there is a database called Newsdb in the Sqlservcer database.
A Java class is a class that is specifically used to manipulate the operation configuration file, which is named: Propertiesutils.java; the code in its class is:
Import java.io.IOException;
Import Java.io.InputStream;
Import java.util.Properties;
public class Propertiesutils {
//Generate an Action profile object
static Properties prop = new Properties ();
/** *
* @param filename needs to load the properties file, the file needs to be placed in the SRC root directory
* @return whether to load success/public
Static Boolean LoadFile (String fileName) {
try {
prop.load (PropertiesUtils.class.getClassLoader (). getResourceAsStream ( FileName));
} catch (IOException e) {
e.printstacktrace ();
return false;
}
return true;
}
/**
* Retrieve the corresponding value
* @param key
* @return/Public
static string GetPropertyValue according to key (string Key) {return
prop.getproperty (key);
}
}
This class provides two methods, one for loading the operation configuration file, and one for reading the values in the file based on the key keys.
The other Java class is the database connection class, named Connectionutils.java, whose code is as follows:
Import java.sql.Connection;
Import Java.sql.DriverManager;
Import java.sql.SQLException;
Import Com.accp.news.utils.PropertiesUtils;
public class Connectionutils {
private static String URL = null;
private static String USER = null;
private static String PWD = null;
static {
Propertiesutils.loadfile ("dbconfig.properties");
url = propertiesutils.getpropertyvalue ("url");
user = Propertiesutils.getpropertyvalue ("user");
PWD = Propertiesutils.getpropertyvalue ("PWD");
try {
class.forname ("Net.sourceforge.jtds.jdbc.Driver");
} catch (ClassNotFoundException e) {
E.printstacktrace ();
}
/**
* Get Connection Tool method
* @return
/public
static Connection getconnection () {
try {
Connection conn = drivermanager.getconnection (URL, USER, PWD);
return conn;
} catch (SQLException e) {
e.printstacktrace ();
}
return null;
}
}
This data connection class, which has a static block that performs the read and drive loading of the configuration file, also provides a way to get a database connection.
Source: http://gongyanghui1986.blog.163.com/blog/static/1374853192010925105210958/