Java JDBC uses the configuration file to connect to the database:
Create a file with the suffix ". properties". The file content includes: Database driver, connected database address, user name, password ......
Take Mysql as an example to create the config. properties configuration file. Its content is as follows:
DRIVER_CLASS = com. mysql. jdbc. Driver
CONNECTION_URL = jdbc: mysql: // localhost: 3306/test
CONNECTION_USERNAME = root
CONNECTION_PASSWORD = root
Create a database connection class:
For example:
Public class ConnectionFactory {
Private static Properties prop;
Private static final String CONFIGNAME = "config. properties ";
Private static List <Connection> conns;
Private Connection conn;
Public JDBCFactory () throws Exception {
Conns = new ArrayList <Connection> ();
Prop = new Properties ();
// Load the configuration file
Prop. load (this. getClass (). getResourceAsStream (CONFIGNAME ));
// Obtain the database driver
Class. forName (prop. getProperty ("DRIVER_CLASS "));
// Create ten database connections and add them to the List set (conns ),
// The list set (conns) is equivalent to a database connection pool with ten database connections.
For (int I = 0; I <10; I ++ ){
Conn = DriverManager. getConnection (
Prop. getProperty ("CONNECTION_URL "),
Prop. getProperty ("CONNECTION_USERNAME "),
Prop. getProperty ("CONNECTION_PASSWORD "));
Conns. add (conn );
}
}
// Obtain the database connection from the List set (conns)
Public Connection getConnection (){
Return conns. remove (0 );
}
// The used database connection is added to the List set (conns ).
Public void close (Connection conn ){
If (conn! = Null ){
Conns. add (conn );
}
}
}
Define the test class:
Public class JDBCTest {
Public static void main (String [] args) throws Exception {
// Create a ConnectionFactory object and a database connection pool
ConnectionFactory cf = new ConnectionFactory ();
// Obtain the database connection
Connection conn = cf. getConnection ();
// Select SQL statement
PreparedStatement ps = conn. prepareStatement ("select * from user ");
// Execute the SQL statement
ResultSet rs = ps.exe cuteQuery ();
// Cyclically input the queried content
While (rs. next ()){
// Id username password is the database query field
System. out. println ("id:" + rs. getInt ("id") +
"Username:" + rs. getString ("username") +
"Password:" + rs. getString ("password "));
}
}
}