Home  >  Article  >  Java  >  Example of introducing dynamic parameters of PreparedStatement

Example of introducing dynamic parameters of PreparedStatement

零下一度
零下一度Original
2017-06-25 11:05:062512browse

1.PreparedStatement Overview

In the operation process of the database, the PreparedStatement object is a very inconspicuous but important interface object. It inherits from Statement and differs from it in two aspects:

1) PreparedStatement instances contain compiled SQL statements. This is what makes the statement "ready". A SQL statement contained in a PreparedStatement object can have one or more IN parameters. The value of the IN parameter is not specified when the SQL statement is created. Instead, the statement reserves a question mark ("?") as a placeholder for each IN parameter. The value of each question mark must be provided through the appropriate setXXX method before the statement is executed.

2) Because the PreparedStatement object has been precompiled, its execution speed is faster than the Statement object. Therefore, SQL statements that are executed multiple times are often created as PreparedStatement objects to improve efficiency.

2. PreparedStatement application example

2.1 The first step is to import the jar package

2.2 Create table t1

 1 <body> 2 <% 3 //加载数据库驱动给jdbc 4 Class.forName("org.gjt.mm.mysql.Driver"); 5 out.print("成功加载驱动"); 6 String url ="jdbc:mysql://127.0.0.1:3306/datebase?user=root&password=123456"; 7 //获取数据库连接,让java可以操作mysql 8 Connection conn = DriverManager.getConnection(url); 9 //定义一条SQL命令创建一个名为t1的表10 String sql = "create table t1(sno varchar(20),name varchar(20),birth String)";11 //从connection对象中,获取一个sql执行者12 PreparedStatement ps = conn.prepareStatement(sql);13 //执行14 ps.execute();15 out.print( conn );16 //首先关闭连接18 ps.close();19 conn.close();20 %>21 22 </body>

2.3 To operate the data in the t1 table, you only need to replace the sql command drop

<%
String sno="1";
String name="小明";
String birth="2008-08-24";
Class.forName("org.gjt.mm.mysql.Driver""成功加载驱动"="jdbc:mysql://127.0.0.1:3306/datebase?user=root&password=123456"Connection conn =PreparedStatement ps =123%>
</body>

//Add information
String sql="insert into t1(sno,name,birth) values(?,?,?)";

//Change information
String sql1="UPDATE t1 SET birth=? where sno=?";

//Delete information
String sql2="delete from t1 where sno=?";

The above is the detailed content of Example of introducing dynamic parameters of PreparedStatement. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn