/**
* 作者:徐守威
* 功能:PreparedStatement演示.
* 1.PreparedStatement可以提高执行效率,因为它有预编译的功能
* 2.PreparedStatement可以防止sql注入,但是要求用?赋值的方式可以
* 时间:2012-11-8
*
*/
package com.test1;
import java.sql.*;
public class Test2 {
/**
* @param args
*/
public static void main(String[] args) {
//定义需要对象
PreparedStatement ps=null;
ResultSet rs=null;
Connection ct=null;
try{
//1.加载驱动
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
ct=DriverManager.getConnection("jdbc:odbc:mytest","sa","xushouwei");
/*ps=ct.prepareStatement("select * from dept where deptno=? and loc=?");
ps.setInt(1, 20);
ps.setString(2, "canada");
rs=ps.executeQuery();
while(rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
}*/
//使用PreparedStatement添加一条记录
ps=ct.prepareStatement("insert into dept values(?,?,?)");
ps.setInt(1,50);
ps.setString(2, "安全部");
ps.setString(3, "南京");
//执行
int i=ps.executeUpdate();
if(i==1){
System.out.println("添加成功");
}else{
System.out.println("添加失败");
}
}catch(Exception e){
e.printStackTrace();
}finally{
//关闭资源
//关闭顺序:谁后创建谁先关闭
try {
//为了程序健壮
if(rs!=null){
rs.close();
}
if(ps!=null){
ps.close();
}
//sm.close();
if(ct!=null){
ct.close();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}