Statement和PreparedStatement的对比

Statement和PreparedStatement的对比

在这里插入图片描述
总之,在开发过程中,如果需要SQL注入(需要拼接SQL语句),就必须使用Statement;如果只是给SQL语句传值的话,使用PreparedStatement。以下代码就是必须使用Statement,因为需要字符串的拼接。

import java.sql.*;
import java.util.ResourceBundle;
import java.util.Scanner;

public class Statement_Preparedstment {
    public static void main(String[] args) {
        //对表格emp中的ename进行排序
        //用户在控制台输入desc是降序,asc是升序
        Scanner s=new Scanner(System.in);
        System.out.print("输入desc表示降序,asc表示升序,请输入dasc/asc:");
        String keyword=s.nextLine();

        //使用资源绑定器绑定资源配置文件
        ResourceBundle bundle=ResourceBundle.getBundle("jdbc");
        String driver=bundle.getString("driver");
        String url=bundle.getString("url");
        String user=bundle.getString("user");
        String password=bundle.getString("password");
        //JDBC编程
        Connection cnn=null;
        Statement stmt=null;
        ResultSet res=null;

        try {
            //注册驱动
            Class.forName(driver);
            //第二步:获取连接
            cnn= DriverManager.getConnection(url,user,password);
            //获取数据库操作对象
            stmt=cnn.createStatement();
            //执行SQL语句
            String sql="select ename from emp order by ename "+keyword;
            res=stmt.executeQuery(sql);
            //处理查询结果集
            while(res.next()){
                System.out.println(res.getString("ename"));
            }

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            //关闭资源
            if (res != null) {
                try {
                    res.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (stmt != null) {
                try {
                    stmt.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (cnn != null) {
                try {
                    cnn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

注意:上面的代码只是一个小小的例子,在实际的开发中,比如某宝界面按价格升序,排序,就相当于是给sql 语句后面拼接 sql order by** desc/asc,要拼接SQL语句的关键字desc/asc,就只能使用Statement。

总结:

在开发过程中,如果需要SQL注入(需要拼接SQL语句),就必须使用Statement,但是Statement效率不太高(编译一次,执行一次)。

在不需要sql 语句拼接的时候,也就是需要避免SQL注入的时候,选择PreparedStatement。当然PreparedStatement还有效率高的好处(编译一次,执行n次)

两个各有利弊,按需选择吧!!!!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值