Java JDBC study notes

1.JDBC 

   Java DataBasue Connectivity, java and database API connection;

   May be connected to different databases in different database loading "driver"

The basic operation of the database steps 2.JDBC

  Import database driver class corresponding to the development

 1) registration drive: Class.forName ( "com.mysql.jdbc.Driver")

 2) create a connection: Connection conn = DriverManager.getConnection (url, user, pass);

 3) Create a sql statement:

     Use Statement

ST = the Statement null ;
 // Get for transmitting sql statement to the database Statement 
ST = conn.createStatement ();
 // send to the database sql 
String sql = "SELECT ID, name, password, In Email, Birthday from Users" ; 
ST .executeQuery (sql);

     Use PrepareStatement: sql injection to avoid problems

ST = PreperedStatement null ; 
String sql = "? The SELECT * from the Users and the WHERE name = password =?" ; 
 
// get used to send sql statement to the database Preperedstatement 
ST = conn.preparedStatement (sql); // In this biography into, precompiled 
st.setString (. 1 , username); 
st.setString ( 2 , password);
 // send to the database sql 
st.executeQuery (); // needed here incoming sql

4) execute statement: Result rs = st.executeQuery ();

5) Close the resource: After creating the first closing

if (pr!=null) {
   pr.close();
}
if (rs!=null) {
    rs.close();
}
if (con!=null) {
   con.close();
}

3. Package JDBC

  Import data source and driving

  

 

   1) Profile lib.properties

druid.url=jdbc:mysql://localhost:3306/jdbc_db?useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true
druid.username=root
druid.password=1234

  2) JDBC package file JdbcUtil.java

Package com.dxj.util;
 Import a java.io.FileInputStream;
 Import java.io.IOException;
 Import the java.sql.Connection;
 Import java.sql.PreparedStatement;
 Import the java.sql.ResultSet;
 Import java.sql.SQLException;
 Import the java.util.Properties; 

Import com.alibaba.druid.pool.DruidDataSource;
 / ** 
 * package the JDBC 
 * @author Administrator 
 * 
 * / 
public  class JdbcUtil {
     // Create a data source object 
    Private  static DruidDataSource DS;
     // create a connection object
    Private  static Connection CON;
     // Create Object PrepareStatement 
    Private  static the PreparedStatement PR;
     // use query 
    Private  static the ResultSet RS; 
    
    static { 
        the init (); 
    } 
    
    / ** 
     * Create a data source object, reads the configuration file 
     * / 
    public  static  void the init () {
         // Ali data source Druid 
        DS = new new DruidDataSource (); 
        
        the Properties Pro = new new the Properties ();
         the try {
             // read the configuration file 
            pro.load (new new the FileInputStream ( "COM \\ DXJ the src \\ \\ \\ lib.properties Resource" )); 
        } the catch (IOException E) { 
            e.printStackTrace (); 
        } 
        // profile 
        ds.configFromPropety (Pro); 
    } 
    
    / ** 
     * Get Connection () the object 
     * / 
    public  static  void Connect () {
         the try { 
            CON = ds.getConnection (); 
        } the catch (SQLException E) { 
            e.printStackTrace (); 
        } 
    } 
    
    / ** 
     * Get Object PrepareStatement 
     *@param sql
     * @param values
     */
    public static void prepareStatement(String sql ,Object ...values) {
        try {
            pr=con.prepareStatement(sql);
            for (int i = 0; i < values.length; i++) {
                pr.setObject(i+1, values[i]);
            }
        } catch (SQLException e) {
            
            e.printStackTrace();
        }
        
    }
    /**
     * 执行增、删、改
     */
    public static void Update () {
         the try { 
            pr.executeUpdate (); 
        } the catch (SQLException E) { 
            e.printStackTrace (); 
        } 
    } 
    
    / ** 
     * make queries 
     * @return 
     * / 
    public  static the ResultSet Query () {
         the try { 
            RS = pr.executeQuery (); 
        } the catch (SQLException E) { 
            e.printStackTrace (); 
        } 
        return RS; 
    } 
    
    / ** 
     * closing operation 
     * / 
    public static void close() {
        try {
            if (rs!=null) {
                rs.close();
            }
            if (pr!=null) {
                pr.close();
            }
            if (con!=null) {
                con.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }    
}

3) Testing

package com.dxj.test;
import java.util.Random;
import com.dxj.util.JdbcUtil;
public class JianTest {

    public static void main(String[] args) {
        Random ran=new Random();
        JdbcUtil.connect();
        String jian="delete from test01_tab where u_id>?";
        JdbcUtil.prepareStatement(jian,"5210");
        JdbcUtil.update();
        JdbcUtil.close();
    }

}

4. database connection pool

    Because creating connections and connection release has a lot of overhead (especially when the database server is not local, every time a connection needs to be TCP three-way handshake, the release of TCP connections require four-way handshake, the overhead caused can not be ignored) in order to improve the performance of the system to access the database, you can create a number of pre-connection in the connection pool, available directly from the connection pool when required, returned at the end of the use of connection pooling without having to close the connection
  Database connection pool connection is created and managed in the pool when the application server starts;
   A connection request by a pool of database connections;
  After the end of the connection request is returned to the pool for later reuse;
  In order to avoid frequent create and release the overhead caused by the connection, which is typical with space for time strategy (waste of storage space connection, but saves the time to create and release connections )
  Pool technology in Java development is very common, to create a thread pool thread when using this same reason
  Java-based open source database connection pool mainly: C3P0, Proxool, DBCP, BoneCP, Druid and so on.
5.JDBC Statement和Preparement
   Compared with Statement:
  1) PreparedStatement interface represents a pre-compiled statement, its main advantage is that it can reduce the SQL compiler errors and increase security of SQL (SQL injection attack to reduce the likelihood of);
  2) PreparedStatement SQL statements can be parameterized, to avoid the trouble and insecurity splice connection with a string of SQL statements;
  3) When the SQL batch or frequent the same query, PreparedStatement has obvious advantages in performance, because the database can be compiled optimized SQL statements cached, the next time the statement is executed the same structure will soon (not again compilation and execution plan)
 

Guess you like

Origin www.cnblogs.com/dxjx/p/12545755.html