使用preparedStatement预编译statement

使用PrepareStatement预编译Statement


import java.sql.*;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * 使用preparedStatement预编译statement,可以是sql语句灵活化
 * @author 可敢离我近点
 *
 */
public class TestPreparedStatement {

	public static void main(String[] args) {
		
		/**
		 * 如果需要在finally块中手动关闭,就需要在try外声明
		 * 如果想要让其自动的关闭,则可以在try后面加一个括号初始化
		 * 先关闭statement,后关闭connection
		 * resultset结果集不需要手动关闭,他会在你关闭statement时自动的关闭
		 */
		Connection con=null;
		PreparedStatement ps = null;
		//初始化驱动
		try {
			Class.forName("com.mysql.jdbc.Driver");
			System.out.println("数据库驱动加载成功...");
			con = DriverManager.getConnection("jdbc:mysql://localhost:3306/xust?useUnicode=true&characterEncoding=utf-8&useSSL=false","root","mysql");
			System.out.println("数据库连接成功...."+con);
			String sql ="select * from area where id= ?;";
			ps = con.prepareStatement(sql);
			ps.setInt(1, 1);
			ResultSet rs = ps.executeQuery();
			if (rs.next()) {
				//字段的顺序从1开始,可以根据字段顺序访问
				//也可以根据字段的名称访问数据
				System.out.println(rs.getString(2)+"......"+rs.getInt("style"));
			}
			System.out.println("ok............");
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			try {
				if (null!=ps) {
					ps.close();
				}
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			try {
				if (null!=con) {
					con.close();
				}
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			System.out.println("yes.............");
		}
	}
	
}

优点:提高灵活性、运行更快、防止SQL注入

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值