第一篇随记:学习WAMP中最基础的JDBC连接操作记录( Statement、PreparedStatement和CallableStatement)

用Statement实现数据库连接:

<%@ page contentType="text/html" pageEncoding="UTF-8" %>
<%@ page import="java.sql.*" %>
<html>  
<head>  
</head>  
<body> 
<!-- 单独写全局! -->
<%!
public static final String DBDRIVER="org.gjt.mm.mysql.Driver";
public static final String DBURL="jdbc:mysql://localhost:3306/test";
public static final String DBUSER="root";
public static final String DBPASS="123456";
%>
<!-- 不在try里定义,为了最后在final里关闭 -->
<%
Connection conn =null;
    Statement stmt = null;
    ResultSet rs = null;
%>

<%
try{
Class.forName(DBDRIVER);
    conn=DriverManager.getConnection(DBURL,DBUSER,DBPASS);
String sql="select empno,ename,job,sal,hiredate from emp";
    stmt=conn.createStatement();
rs=stmt.executeQuery(sql);
%>
<div>
<table border="2dp">
<tr>
<td>a</td>
<td>b</td>
<td>c</td>
<td>d</td>
<td>e</td>
</tr>
<%
while(rs.next()){
int a=rs.getInt(1);
String b=rs.getString(2);
String c=rs.getString(3);
float d=rs.getFloat(4);
java.util.Date e=rs.getDate(5);
%>

<tr>
<td><%=a %></td>
<td><%=b %></td>
<td><%=c %></td>
<td><%=d %></td>
<td><%=e %></td>
</tr>
<%
}
%>

</table>

</div>

<!-- catch在try出错时运行,finally无论如何都运行-->

<%
}catch(Exception e){
System.out.println(e);
}finally{
rs.close();
stmt.close();
conn.close();
}
%>
</body>  

</html>  

实现效果:

关于Statement(接口)、PreparedStatement(接口)、CallableStatement(接口):

以上三者为依次前继承后的关系。


一、Statement:(用于执行不带参数的简单 SQL 语句,用于执行仅一次查询并返回结果的情形,这种情况下效率高于        PreparedStatement,应用如上)

二、PreparedStatement:(用于执行带或不带 IN 参数的预编译SQL 语句)
    a.由于采用Cache机制,则预先编译的语句,就会放在Cache中,下次执行相同SQL语句时,则可以直接从Cache中取出来,效率高;

    b.安全性好,有效防止Sql注入等问题;

    c.对于多次重复执行的语句,使用PreparedStament效率会更高一点,并且在这种情况下也比较适合使用batch;

    d.  代码的可读性和可维护性。

用法1:
    PreparedStatement pstmt  = con.prepareStatement("UPDATE EMPLOYEES  SET SALARY = ? WHERE ID =?");
    pstmt.setBigDecimal(1, 153833.00);
    pstmt.setInt(2, 110592);
    pstmt. executeUpdate();
用法2(批处理):
    PreparedStatement pstmt  = con.prepareStatement("UPDATE EMPLOYEES  SET SALARY = ? WHERE ID =?");
   for(int i =0;i<length;i++){
        pstmt.setBigDecimal(1, param1[i]);
        pstmt.setInt(2, param2[i]);
        pstmt.addBatch();
    }
    pstmt. executeBatch();
 

三、CallableStatement :(用于执行对数据库已存储过程的调用)
      了解不深,后续 不补充

此本仅做个人学习记录,如有错误,请指正。十分感谢

猜你喜欢

转载自blog.csdn.net/monaup/article/details/78384263