Java Foundation - JDBC Accessing Database

Keywords: JDBC Java Database SQL

**

Java Foundation - JDBC Accessing Database

**
JDBC, full name Java DataBase Connectivity. It provides a variety of methods, including access to the database, execution of sql statements and so on. The classes that operate on the database are all in the java.sql package. Here are some steps to link the database through JDBC.

  1. Load the JDBC driver. In fact, this is what we usually call some jar packages. These packages can be found on the official website of the database. There are also some on the Java official website. Generally, about 5/6 packages can be added directly to the classpath of the project. Generally, they are in the WEB-INF/lib directory of the project. (Can't find a contact with me, I can send it to you, I will upload it to CSDN later.)
  2. Load the JDBC driver and register it with Driver Manager. Generally registered by reflection, the approximate grammar is Class. forName (String Drive Name). (Reflection is a way to load classes, and the implementation mechanism will be mentioned in the following blog about Java source code.)
  3. Establish database links to get Connection objects. The general method is DriverManager.getConnection(url,username,passwd) method. The URL represents the string connecting the database. Username is the user name of the database, and passwd is the password of the database.
  4. Establish a Statement or PreparedStatement object.
  5. Executing sql statements
  6. Access the ResultSet object of the result set.
  7. Close the above objects through the. close() method, because the JDBC driver at the bottom is through the network IO to achieve SQL commands and data transmission.

This is a way of thinking about using JDBC. In fact, in real projects, it is impossible to write these procedures every time you visit them. Generally, they are placed in a tool class and called directly when you use them. Next, paste the JDBC tool class that I usually use.

package com.neu.mvc.dao.util;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Properties;

//SessionFactory must be a singleton pattern
public class SessionFactorytemp {
    private static SessionFactorytemp sessionFactory = new SessionFactorytemp();

    private SessionFactorytemp() {
    }

    public static SessionFactorytemp getInstance() {
        return sessionFactory;
    }

    public Connection getSession() throws Exception {
        // 0_1 Loads Configuration Information through Property Files
        Properties props = new Properties();
        InputStream in = SessionFactorytemp.class.getClassLoader()
                .getResourceAsStream("db.properties");
        props.load(in);
        in.close();
        // 1-Load Driver
        Class.forName(props.getProperty("jdbc.DBDriver"));
        // 2 - Connect database according to url, username, password
        String url = props.getProperty("jdbc.url");
        String username = props.getProperty("jdbc.username");
        String password = props.getProperty("jdbc.password");
        Connection con = DriverManager.getConnection(url, username, password);
        // 3-Return connection
        return con;
    }

    public void close(ResultSet rs, Statement ps, Connection con)
            throws Exception {
        if (rs != null)
            rs.close();
        if (ps != null)
            ps.close();
        if (con != null)
            con.close();
    }
}

The above is a common tool class connecting database through JDBC, encapsulated in a class, which is more convenient to call. But in the project we may also use the connection pool (do not know Baidu), if we use the connection pool, the above classes need to be changed.
I usually use the c3p0 connection pool, and paste the tool class of the c3p0 connection pool below, but to really use the c3p0 connection pool, it is necessary to create configuration files and corresponding drivers, that is, jar packages. This tool class uses the singleton pattern.

package com.neu.mvc.dao.util;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

import com.mchange.v2.c3p0.ComboPooledDataSource;

//SessionFactory must be a singleton pattern
public class SessionFactory {
    //Singleton mode
    private static SessionFactory sessionFactory = new SessionFactory();
    private SessionFactory() {
        cpds = new ComboPooledDataSource("java_C3P0");
    }
    public static SessionFactory getInstance() {
        return sessionFactory;
    }
    //Configuring Data Source Connection Pool C3P0
    private ComboPooledDataSource cpds;
    //Get connections from connection pools

    public Connection getSession() throws Exception {
         System.out.println("Connection pool information:" + cpds);
         return cpds.getConnection();
    }

    public void close(ResultSet rs, Statement ps, Connection con)
            throws Exception {
        if (rs != null)
            rs.close();
        if (ps != null)
            ps.close();
        if (con != null)
            con.close();
    }
}

Forget it. Stick the configuration file on it, too.

<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
       <named-config name="java_C3P0">
            <!-- Connect the connection pool to the database so that the database can be connected con Objects put into connection pool -->
              <property name="user">liang</property>
              <property name="password">tiger</property>
              <property name="driverClass">oracle.jdbc.driver.OracleDriver</property>
              <property name="jdbcUrl">jdbc:oracle:thin:@127.0.0.1:1521:ORCL</property>
            <!-- Yes Connection Configuration of the number of objects in the connection pool -->
              <property name="initialPoolSize">10</property>
              <property name="minPoolSize">10</property>
              <property name="maxPoolSize">50</property>
              <property name="acquireIncrement">10</property>
             <!-- Yes PreparedStatement Objects and Statement Configuration of the number of objects in the connection pool -->
              <property name="maxStatements">20</property>
              <property name="maxStatementsPerConnection">5</property>
       </named-config>
</c3p0-config>

Finally, if you configure the c3p0 connection pool, don't forget the jar package!!
If you don't understand, please contact me through the connection in CSDN.

Posted by WD.Gh0st on Mon, 15 Apr 2019 23:24:32 -0700