The relationship and difference between Statement and PreparedStatement

Source: Internet
Author: User

The relationship and distinction between Statement and PreparedStatement.
Relationship: PreparedStatement inherits from statement, all interfaces
Difference: PreparedStatement can use placeholders, are precompiled, batch processing is higher than statement efficiency
Detailed
1, PreparedStatement: An object representing the precompiled SQL statement.
Interfaces: Inheritance relationship between public interface PreparedStatement extends statement
The SQL statement is precompiled and stored in the PreparedStatement object. You can then use this object to execute the statement more efficiently than once.
Note: The setting method used to set in parameter values (Setshort, setstring, and so on) must specify a type that is compatible with the defined SQL type of the input parameter. For example, if the in parameter has an INTEGER of SQL type, then the Setint method should be used, and the position of the question mark should be noted, because the first greeting is 1, and the second question mark is 2. And so on.
If any parameter type conversion is required, the target SQL type should be used as its parameter when using the SetObject method.
In the following example of setting a parameter, con represents an active connection:
PreparedStatement pstmt = con.preparestatement ("UPDATE EMPLOYEES SALARY =? WHERE ID =? ");
Pstmt.setbigdecimal (1, 1533.00)
Pstmt.setint (2, 1102)
Pstmt.execute ()//Note that there can be no more SQL statements here, unlike statment

Demo Code:

Import java.sql.Connection;
Import Java.sql.DriverManager;
Import java.sql.PreparedStatement;
Import java.sql.SQLException;
Import java.sql.Statement;
	public class Preparedstatementtest {public static void main (string[] args) {test_autocommit ();
		public static void Test_autocommit () {String driver= "oracle.jdbc.driver.OracleDriver";
		String url= "JDBC:ORACLE:THIN:@127.0.0.1:1521:ORCL";
		String user= "Briup";
		String password= "Briup";
		Connection Conn=null;
		PreparedStatement Ps=null;
			try {//1, Registered driver Class.forName (driver);
			 2, get the connection conn= drivermanager.getconnection (URL, user, password);
			SYSTEM.OUT.PRINTLN (conn);
			 3, create preparestatement object String sql= "insert INTO lover values (?,?,?)";
			 Ps=conn.preparestatement (SQL); 4. Execute SQL statement ps.setint (1,21);//Represents ps.setstring (2, "suwu150") with the value of type int set to the first?? The value of the number position is a string type suwu150 java.util.Date utildate=new java.util.Date ();//type conversion, converted from util type Date to ps.setdate of SQL type (3, n EW java.Sql.
			 Date (Utildate.gettime ())); Ps.execute ()///Execution System.out.println (Ps.execute ());//The result returned by the table output is false because there is no result set returned//5, processing result set} catch (Excepti
		On e) {e.printstacktrace ();
			finally{//6, close resource try {if (ps!=null) ps.close ();
			catch (SQLException e) {e.printstacktrace ();
			try {if (conn!=null) conn.close ();
			catch (SQLException e) {e.printstacktrace ();	 }
		}
	}
}

Results after insertion



2, Statement: An object that executes a static SQL statement and returns the results it generates.
Interface: public interface Statement extends wrapper
By default, each Statement object can open only one ResultSet object at the same time. Therefore, if you read a ResultSet object that intersects with another, the two objects must be generated by a different Statement object. If there is an open current ResultSet object for a statement, all execution methods in the Statement interface will implicitly close it.
Create a statement object as follows:
Statement stat=conn.createstatement ();
String sql= "INSERT INTO lover values (6, ' suxingxing ', to_date (' 21-9-2016 ', ' dd-mm-yyyy ')");
Stat.execute (SQL);//There should be SQL statements here, unlike preparedstatment
Take a look at the actual use of it:

Import java.sql.Connection;
Import Java.sql.DriverManager;
Import java.sql.SQLException;
Import java.sql.Statement;
	public class Statementtest {public static void main (string[] args) {test_autocommit ();
        public static void Test_autocommit () {String driver= "oracle.jdbc.driver.OracleDriver";
        String url= "JDBC:ORACLE:THIN:@127.0.0.1:1521:ORCL";
        String user= "Briup";
        String password= "Briup";
        Connection Conn=null;
        Statement Stat=null;
            try {//1, Registered driver Class.forName (driver);
             2, get the connection conn= drivermanager.getconnection (URL, user, password);
             Conn.setautocommit (FALSE);
            SYSTEM.OUT.PRINTLN (conn);
             3, Create statement object Stat=conn.createstatement (); 4, Execute SQL statement String sql= "insert into lover values (, ' suxingxing ', to_date (' 21-9-2016 ', ' dd-mm-yyyy ')");
           Note Format//stat.execute (SQL);  SYSTEM.OUT.PRINTLN (Stat.execute (SQL));
             The return value is false because there is also no resultset return set Conn.commit ();
            5. Processing result set} catch (Exception e) {e.printstacktrace ();
            try {conn.rollback ();
            catch (SQLException E1) {e1.printstacktrace ();
            } finally{//6, close resource try {if (stat!=null) stat.close ();
            catch (SQLException e) {e.printstacktrace ();
            try {if (conn!=null) conn.close ();
            catch (SQLException e) {e.printstacktrace ();
 }
        }
    }
}
Results after insertion:



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.