首页 > 数据库技术 > 详细

使用PreparedStatement接口操作数据库

时间:2017-06-10 23:07:25      阅读:189      评论:0      收藏:0      [点我收藏+]
从代码来看,用PreparedStatement来代替Statement会使代码多出几行,但这样的代码无论从可读性还是可维护性上来说,都比直接用Statement的代码高很多档次。

传递给PreparedStatement对象的参数可以被强制进行类型转换,使开发人员可以确保在插入或查询数据时与底层的数据库格式匹配。
在公共web站点环境下,有恶意的用户会利用那些设计不完善的、不能正确处理字符串的应用程序来个SQl注入,使用PreparedStatement安全性更高。

package cn.bdqn.demo;

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

public class Demo3 {
public static void main(String[] args) {
Connection conn = null;
PreparedStatement pstmt =null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/myschool", "root", "0000");
System.out.println(conn);
pstmt = conn.prepareStatement("select * from student where StudentName=? and LoginPwd=?");
pstmt.setString(1, "郭靖");
pstmt.setString(2, "111111");
rs = pstmt.executeQuery();
while(rs.next()){
//查询获取字段值

}
} catch (Exception e) {
e.printStackTrace();
}finally{
//释放资源
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
rs = null;
}
if(pstmt!=null){
try {
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
pstmt = null;
}
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
conn = null;
}
}
}
}

使用PreparedStatement接口操作数据库

原文:http://www.cnblogs.com/wxbblogs/p/6980094.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!