PreparedStatement接口
 继承于Statement
 但是却拥有更安全更高效率的方法
具体如下1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49/**
 * 此代码演示了PreparedStatement类
 * */
public class PreparedStatementDemo {
    public static void main(String[] args) {
        try
        {
            Class.forName("com.mysql.cj.jdbc.Driver");
            Connection conn =
                    DriverManager.getConnection("jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT", "root", "wangxv123");
            // 此处的 ? 是代表占位符
            //为了避免SQL的风险,PreparedStatement中使用占位符来先保证参数
            String sql = "INSERT INTO students (sid,NAME,sage) VALUES (?,?,?);";
            PreparedStatement pst = conn.prepareStatement(sql);
            //然后在使用set****等各种方法给参数赋值,因为规定了类型,所以可以避免SQL注入的风险
            pst.setInt(1,006);
            pst.setString(2,"哈哈");
            pst.setInt(3,22);
			 //也可以使用  pst.setObject   此方法的好处是不需要知道具体类型
            pst.execute();
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException ex){
            ex.printStackTrace();
        }finally
        {   
            //关闭PreparedStatement
            try{
                if(pst!=null) {
                    pst.close();
                }
            }catch (SQLException se)
            {
                se.printStackTrace();
            }
            //关闭Connect
            try {
                if(conn!=null)
                {
                    conn.close();
                }
            }catch (SQLException e)
            {
                e.printStackTrace();
            }
        }
    }
}