Statement和PreparedStatement的使用

/**
 * @author wht
 *
 */
public class PreparedStatementTest {
	
public static void main(String[] args) {
	
		// TODO Auto-generated method stub
		Connection connection=null;
		  PreparedStatement preparedStatement=null;
		  ResultSet result=null;
		try {
			//1注册驱动
			Class.forName("com.mysql.cj.jdbc.Driver");
			//2建立数据连接对象
		    connection= DriverManager.getConnection("jdbc:mysql://localhost:3306/wht?serverTimezone=GMT", "root", "root");
		    
		    String sql="select * from test where name=?";
		    //3预编译sql语句并设值
			preparedStatement=connection.prepareStatement(sql);
			preparedStatement.setString(1, "张三");
//			//4执行sql语句
			result=preparedStatement.executeQuery();
			//5查询结果集
			while(result.next()) {
				System.out.println(result.getString("name")+":"+result.getString("password"));
			}
			//6释放资源
			
			
			
				
				
			
			
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			
			if(preparedStatement!=null) {
				try {
					preparedStatement.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	  }
	

}

PreparedStatement是预编译sql语句,先把框架弄好,然后再框架里面设置,做到了sql语句和用户的值处于泾渭分明的状态(防止sql注入,把传入的东西都不当成sql语句),虽然现在大部分都用PreparedSta类但Statemen也有自己的价值,如:Statement可以让用户自己写sql语句进行注入(降升序语句),这就是利用了字符串的拼接利用sql注入来达到目的
二者的选择在于你传入的sql语句的东西是个实在的值还是sql语句的词汇

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值