Chinaunix首页 | 论坛 | 博客
  • 博客访问: 168517
  • 博文数量: 60
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 466
  • 用 户 组: 普通用户
  • 注册时间: 2013-09-08 21:46
个人简介

我是个笨蛋

文章分类

全部博文(60)

文章存档

2015年(22)

2014年(20)

2013年(18)

我的朋友

分类: Java

2014-03-19 09:46:14

//使用PreparedStatement进行crud操作
//1.PreparedStatement可以提高执行效率(因为有预编译功能)
//2.PreparedStatement可以防止sql注入,但是要求使用?赋值的方式才可以

package com.test1;

import java.sql.*;

public class Test2 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        //定义需要的对象
        PreparedStatement pst = null;
        ResultSet rs = null;
        Connection conn = null;
        try {
            //1.加载驱动
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            //2.得到连接
            conn = DriverManager.getConnection("jdbc:odbc:mytest");
            //3.创建pst
//            pst = conn.prepareStatement("select * from users where username=? and passwd=?");
//            //给?赋值
//            pst.setString(1, "aaa");
//            pst.setString(2, "'shfa' or 1='1'");
//            //上面的语句用PreparedStatement得不到任何结果,防止sql注入
//            
//            //但是下面的语句不能防止sql注入
//            //pst = conn.prepareStatement("select * from users where username='aaa' and passwd='shfa' or 1='1'");
//            
//            rs = pst.executeQuery();
//            while(rs.next()) {
//                System.out.println("ok");
//                //System.out.println(rs.getInt(1) +" "+ rs.getString(2) +" "+ rs.getString(3));
//            }
            //使用PreparedStatement添加一条记录
            pst = conn.prepareStatement("insert into dept values(?,?,?)");
            pst.setInt(1, 50);
            pst.setString(2, "安全部");
            pst.setString(3, "北京");
            //执行
            int i = pst.executeUpdate();
            if(i == 1) {
                System.out.println("添加ok");
            } else {
                System.out.println("添加不ok");
            }
            
        } catch(Exception e) {
            e.printStackTrace();
        } finally {
            //关闭资源
            //关闭顺序是谁后创建谁先关闭
            try {
                //为了程序健壮
                if(rs != null) {
                    rs.close();
                }
                if(pst != null) {
                    pst.close();
                }
                if(conn != null) {
                    conn.close();
                }
                
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        
    }

}

阅读(1002) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~