PreparedStatement与Statement区分

Statement 和 PreparedStatement 的区别:
添加或者更新的时候,尽量使用 PreparedStatement ,而不是使用Statement。
Statement用于执行静态SQL语句,在执行的时候,必须指定一个事先准备好的SQL语句,并且相对不安全,会有SQL注入的风险。
PreparedStatement是预编译的SQL语句对象,sql语句被预编译并保存在对象中, 被封装的sql语句中可以使用动态包含的参数。
使用PreparedStatement对象执行sql的时候,sql被数据库进行预编译和预解析,然后被放到缓冲区,每当执行同一个PreparedStatement对象时,他就会被解析一次,但不会被再次编译 可以重复使用,可以减少编译次数,提高数据库性能
且能够避免SQL注入,相对安全(把’ 单引号 使用 \ 转义,避免SQL注入 )。
实例:使用PreparedStatement 执行查询

public static void load(int id) {

		Connection conn = null;
		PreparedStatement prst = null;
		ResultSet rs = null;
		try {
			// 1 加载驱动
			Class.forName("com.mysql.jdbc.Driver");
			// 2 创建数据库连接对象
			conn = DriverManager.getConnection(
					"jdbc:mysql://127.0.0.1:3306/da", "root", "root");

			// 这里我们用? 问号代替值,可以叫占位符,也可以叫通配符
			String sql = "select * from test_jdbc where id = ?";
			// 3 语句传输对象
			prst = conn.prepareStatement(sql);
			// 设置第一个?的值
			prst.setInt(1, id);
			rs = prst.executeQuery();
			while (rs.next()) {
				System.out.print(rs.getInt("id") + "   ");
				System.out.print(rs.getString("name") + "   ");
				System.out.println(rs.getString("money") + "   ");
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				// 关闭资源,从上到下依次关闭,后打开的先关闭
				if (rs != null) {
					rs.close();
				}
				if (prst != null) {
					prst.close();
				}
				if (conn != null) {
					conn.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
	}

以上的代码我们每个方法中都会部分重复一次,这是没必要的,因为不同的方法其实只是具体执行的SQL语句的内容不同,对于获取连接与释放资源,对应的逻辑是相同的。我们完全可以把这一段逻辑抽取出来,形成独立的类与方法,再在实际应用时调用对应的类和方法就可以了。

创建链接这些可以这样进行优化
	public static Connection getConnection() throws ClassNotFoundException,
			SQLException {
		String username = "root";
		String password = "root";
		String url = "jdbc:mysql://127.0.0.1:3306/da";

		Class.forName("com.mysql.jdbc.Driver");
		Connection connection = DriverManager.getConnection(url, username,
				password);

		return connection;
	}

关闭资源这些可以这样进行优化
因为Connection和Statement/PreparedStatement以及ResultSet都实现了AutoCloseable接口
所以我们可以直接写AutoCloseable

	public static void close(AutoCloseable obj) {
		if (obj != null) {
			try {
				obj.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值