JDBC(3): PreparedStatement interface

Reference http://study.163.com/course/courseLearn.htm?courseId=1455026#/learn/video?lessonId=1821070&courseId=1455026

1. Statement interface problem

Although the Statement interface is provided in JDBC, in fact, the Statement interface has serious operational flaws and will not be used in work
Example : Observe the Statement interface problem

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;



public class TestDemo {
    private static final String DBDRIVER = "oracle.jdbc.driver.OracleDriver";
    private static final String DBURL = "jdbc:oracle:thin:@localhost:1521:mldn";
    private static final String USER = "scott";
    private static final String PASSWORD = "tiger";
    public static void main(String[] args) throws Exception {
        String name = "Mr'SMITH";
        String birthday = "1998-10-10";
        int age = 18;
        String note = "是个外国人";
        //第一步:加载数据库驱动程序,此时不需要实例化,因为会由容器自己负责管理
        Class.forName(DBDRIVER);
        //第二步:连接数据库
        Connection conn = DriverManager.getConnection(DBURL, USER, PASSWORD);
        //第三步

        Statement stmt = conn.createStatement();
        String sql = "INSERT INTO member(mid,name,birthday,age,note) VALUES "
                + " (myseq.nextval,'"+name+"', TO_DATE('"+birthday+"','yyyy-mm-dd'),"
                + age + ", '" + note+"')";
        System.out.println(sql);
        int len = stmt.executeUpdate(sql);
        System.out.println("影响的数据行:" + len);
        //在编写SQL语句的过程里,如果太长的时候需要换行,那么应当前后加上空格,避免出错

        conn.close();

    }

}

In general, the basic information is entered separately, and the above code will finally form the SQL statement string.
But the result of running the above program will report an error

INSERT INTO member(mid,name,birthday,age,note) VALUES  (myseq.nextval,'Mr'SMITH', TO_DATE('1998-10-10','yyyy-mm-dd'),18, '是个外国人')
Exception in thread "main" java.sql.SQLSyntaxErrorException: ORA-00917: 缺失逗号

The reason for the error is that the username contains a ' sign.
If Statement is to be applied flexibly, it must be completed in the form of a pieced string, but if the input content contains "'", then the entire SQL will be wrong, that is to say, the execution mode of Statement is not suitable for processing some sensitive characters. So you can't use the Statement interface.

PreparedStatement operations

The key problem of Statement execution is that it requires a complete string to define the SQL statement to be used, so this leads to a lot of word SQL piecing in use. The difference between PreStatement and Statement is that it executes It is a complete SQL statement with special placeholder tags and can dynamically set the required data.

PreparedStatement is a sub-interface of Statement, but if you want to get the instantiated object of this word interface, you still need to use the methods provided by the Connection interface.

* public PreparedStatement prepareStatement(String sql) throws SQLException*
(note that the method name does not contain "d")
, an SQL statement needs to be passed in. This SQL is a complete SQL with a special mark, but there is no content at this time. A series of setXXX() methods are required to set the specific content for the tags used, and then you can:
Update operation: int executeUpdate() throws SQLException
Query operation: ResultSet executeQuery() throws SQLException
The above methods do not need to receive SQL statements
when used The most important thing to pay attention to when operating the PreStatement interface is the setDate() method inside, because this method uses java.sql.Date instead of java.util.Date.
There are three subclasses under the java.util.Date class. In the java.sql package:
java.sql.Date: describes the date;
java.sql.Time: describes the time:
java.sql.Timestamp: describes the timestamp (date and time).
If you want to change java.util.Date to java.sql.Date(Time, Timestamp), you can only rely on long to complete.
java.util.Date: public long getTime(), you can turn Date into long
java.sql.Date: public Date(long date), and change long into sql.Date.

Example : data augmentation

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.Date;



public class TestDemo {
    private static final String DBDRIVER = "oracle.jdbc.driver.OracleDriver";
    private static final String DBURL = "jdbc:oracle:thin:@localhost:1521:mldn";
    private static final String USER = "scott";
    private static final String PASSWORD = "tiger";
    public static void main(String[] args) throws Exception {
        String name = "Mr'SMITH";
        Date birthday = new Date();
        int age = 18;
        String note = "是个外国人";
        //第一步:加载数据库驱动程序,此时不需要实例化,因为会由容器自己负责管理
        Class.forName(DBDRIVER);
        //第二步:连接数据库
        Connection conn = DriverManager.getConnection(DBURL, USER, PASSWORD);
        //第三步:进行数据库的操作,执行完整的SQL
        String sql = " INSERT INTO member(mid, name, brithday, age, note) VALUES "
                + " (myseq.nextval,?, ?, ? ,?)"; 
        PreparedStatement stmt = conn.prepareStatement(sql);
        stmt.setString(1, name);
        stmt.setDate(2, new java.sql.Date(birthday.getTime()));
        stmt.setInt(3, age);
        stmt.setString(4, note);

        System.out.println(sql);
        int len = stmt.executeUpdate();
        System.out.println("影响的数据行:" + len);
        //在编写SQL语句的过程里,如果太长的时候需要换行,那么应当前后加上空格,避免出错

        conn.close();

    }

}

In this way, sensitive characters can be avoided, and other update methods are the same, and even the query uses the same placeholder method, and then the content is added.

Guess you like

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