java database connection and precautions

jdbc: java database connection, which is the database connection of java.
Function: Complete the interaction between database data and memory data.

In order to shield the differences of different databases, an interface standard is established between memory and various databases. Each vendor implements the interface class according to the interface standard.


jdbc is a set of standards for java to connect to the database. A series of interfaces are defined in this standard, and database manufacturers provide implementation classes according to the characteristics of their own databases, which are called by developers. Developers can call methods according to the interface, which can shield the differences between different database manufacturers. In this way, no matter what database is connected to, it is a set of APIs.

jdbc operation steps: Flow operation steps:
① Load the driver and establish a connection 1. Establish a flow 
② Execute SQL statements 2. Operate the flow
③ Close the connection 3. Close

 

SQL injection: When executing the SQL statement, since the value of the SQL statement is input by the user, it is received as a variable. If the SQL statement is executed by splicing strings, once there are illegal characters or keywords in the data, It will lead to syntax errors or incorrect execution results, which is called SQL injection.


The difference between Statement and PreparedStatement:

Statement is the parent interface of PreparedStatement. When executing an SQL statement, you can only concatenate values ​​by concatenating strings. Will cause SQL injection. And it's inefficient.

PreparedStatement is a precompiled SQL statement execution object. It supports placeholder mode. No matter what the value of the data is, it is treated as a string and will not cause SQL injection. And high efficiency.

 for example:

package database connection;

import java.sql.Date;
/**
 * Citizen entity class
 * @author C
 *
 */ 
public  class ManBean {
     /** citizen number */ 
    private  int id;
     /** name */ 
    private String name;
     /** gender */ 
    private String sex;
     /** birthday */ 
    private Date briyhday;
     public  int getId () {
         return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getSex() {
        return sex;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }
    public Date getBriyhday() {
        return briyhday;
    }
    public void setBriyhday(Date briyhday) {
        this.briyhday = briyhday;
    }
    public ManBean(String name, String sex, Date briyhday) {
        super();
        this.name = name;
        this.sex = sex;
        this.briyhday = briyhday;
    }
    public ManBean() {
        super();
        // TODO Auto-generated constructor stub
    }
    @Override
    public String toString() {
        return "ManBean [id=" + id + ", name=" + name + ", sex=" + sex + ", briyhday=" + briyhday + "]\n";
    }    
}

Emphasis: If a proxy constructor is defined in a class, there is no default no-mistake construct, so a no-mistake construct must be added.

  

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * All Dao parent classes
 *
 * @author C
 *
 */ 
public  class ManDao {
     /** Connection object */ 
    protected Connection con = null ;
     /** Sql statement execution object */ 
    protected PreparedStatement pr = null ;
     /** Result set object */ 
    protected ResultSet rs = null ;

    /**
     * Build a link
     */ 
    public  void setCnnonection() {
         // Load driver 
        try {
            Class.forName( "com.mysql.jdbc.Driver" );
             // Establish a connection
             // jdbc indicates that jdbc needs to be used to establish a connection. mysql indicates the type of connection database, localhost indicates the IP address of the connection server
             // where localhost is the ip of the local machine
             // 3306 indicates the port number of mysql, and mytest1 is the database name in sql, indicating that the database table in this class needs to be used
             // characterEncoding=utf-8 means to set the encoding set of the connection database 
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mytext1?characterEncoding=utf-8", "root" ,
                     "123456" );
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * close the stream
     */
    public void closeConnecting() {
        try {
            if (rs != null) {
                this.rs.close();
            }
            this.pr.close();
            this.con.close();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        ManDao m = new ManDao ();
        m.setCnnonection();

    }

}

Emphasis: It is an abstract behavior to define two methods for establishing a connection and closing a stream in a class, so that it is convenient to directly call its methods when needed without writing repetitive code.

package database connection;

import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * Citizen Persistence Implementation Interface
 * @author C
 *
 */ 
public  class ManDaoImpl extends ManDao implements IManDao {
     public  void add(ManBean man) {    
         // Load driver 
        try {
             this .setCnnonection();
             // Execute sql statement, ? Represents a placeholder, which needs to be filled with data 
             pr= con.prepareStatement(
                     "insert into t_man (manName,sex,brithday) values(?,?,?)" );
             // Take out the name attribute in the man object , fill the first placeholder 
            pr.setString(1 ,man.getName());
            pr.setString( 2 , man.getSex());
            pr.setDate( 3 , man.getBriyhday());            
             // To update the database, you must write 
            pr.executeUpdate();            
        } catch (Exception e) {
            e.printStackTrace ();
        }finally{
            this.closeConnecting();
        }
    }

    /**
     * Find all collections of citizen objects
     */
    public List<ManBean> findall() {
        List<ManBean> list = new ArrayList<ManBean>();
        try {
            this.setCnnonection();
            pr = con.prepareStatement("select *from t_man" );
             // Execute the query operation, encapsulate the data queried by the sql statement in the result set object 
            rs = pr.executeQuery();

            // Point the pointer of the result set to the next record, if the method returns false, it means that the pointer is at the end of the result set. 
            while (rs.next()) {
                ManBean man = new ManBean();
                 // Get the value of the id column in the database and fill in the id attribute of the entity object. "" is the column name 
                man.setId(rs.getInt("id" ));
                man.setName(rs.getString("manName"));
                man.setSex(rs.getString("sex"));
                man.setBriyhday(rs.getDate( "brithday" ));
                 // Add the encapsulated record entity object to the collection 
                list.add(man);

            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            this.closeConnecting();
        }
        return list;
    }

Emphasis: 1. After adding, deleting, and modifying, the database must be updated with the executeUpdate() method. 2. The query must use the result set to pass the data of the database. 3. Finally, the connection must be closed, otherwise it will cause data loss.

 

  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325110942&siteId=291194637