码迷,mamicode.com
首页 > 数据库 > 详细

使用PreparedStatement接口操作数据库

时间:2017-06-10 23:35:05      阅读:278      评论:0      收藏:0      [点我收藏+]

标签:prepare   drive   java   安全性   tps   manage   dem   statement   获取   

从代码来看,用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接口操作数据库

标签:prepare   drive   java   安全性   tps   manage   dem   statement   获取   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!