Before attending the jdbc training class today, instructor Li introduced us to a new friend, Properties. I thought it was a struts. properties file. The result was a collection class, but it was related to. properties.
. Properties property file:
Some fields can be defined and assigned to them in the form of key-value pairs, which does not need to be written in the code, realizing the separation of values and codes, this makes it easy for us to modify the value later.
One of the functions of the Properties collection class is to establish a connection with the. properties or xml file in the project to obtain the value that exists in the form of a key-value Pair written in the properties file.
Example: obtain information about the connected database stored in the properties file.
First column attribute file db. properties
# Oracle
Url = jdbc: oracle: thin: @ localhost: 1521: orcl
Driver = oracle. jdbc. driver. OracleDriver
Username = scott
Password = tiger
# Mysql
# Url = jdbc: mysql: // localhost: 3306/test
# Driver = com. mysql. jdbc. Driver
# Username = root
# Password = root
# Sqlservers
# Url = jdbc: sqlserver: // localhost: 1433; DatabaseName = studb
# Driver = com. microsoft. sqlserver. jdbc. SQLServerDriver
# Username = sa
# Password = sa
Connect to the database in java:
Package com. strong. jdbc. util;
Import java. io. FileInputStream;
Import java. io. FileNotFoundException;
Import java. io. IOException;
Import java. io. InputStream;
Import java. SQL. Connection;
Import java. SQL. DriverManager;
Import java. SQL. SQLException;
Import java. util. Properties;
Public class Test {
Private static String url;
Private static String driver;
Private static String username;
Private static String password;
// Static code block, loaded only once when the program is started for the first time
Static {
Try {
Properties prop = new Properties ();
// The Properties class must first create a file byte stream when obtaining the value in the property File
InputStream is = new FileInputStream ("db. properties ");
Prop. load (is );
// Obtain value through key
Url = prop. getProperty ("url ");
Driver = prop. getProperty ("driver ");
Username = prop. getProperty ("username ");
Password = prop. getProperty ("password ");
} Catch (FileNotFoundException e ){
E. printStackTrace ();
} Catch (IOException e ){
E. printStackTrace ();
}
}
// Connect to the database
Public static Connection getConnection (){
Connection conn = null;
Try {
Class. forName (driver );
Conn = DriverManager. getConnection (url, username, password );
} Catch (ClassNotFoundException e ){
E. printStackTrace ();
} Catch (SQLException e ){
E. printStackTrace ();
}
Return conn;
}
Public static void main (String [] args ){
System. out. println (getConnection ());
}
}