Stamement接口
- 用于执行静态SQL语句并返回它生成结果的对象。
- 三种Stamement:*Stamement:用createStatement创建,用于发送简单的SQL语句。(不带参数) *PreparedStatement: 继承自Statement接口,由prepareStatement创建,用于发送含有 一个或多个输入参数的SQL语句。 (PreparedStatement对象比Statement对象的效率更高 并且可以防止SQL注入,通常都使用这个。) *CallableStatement: 继承自PreparedStatement,由方法prePareCall创建 用于调用存储过程。
- 常用的Statement方法:*execute():运行语句,返回是否有结果集。 *executeQuery():运行select语句,返回ResultSET结果集。 *executeUpdate():运行insert/update/delete操作,返回更新的行数。
***代码样例**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
45public class jdbcDemo {
    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");         
            //创建Statement对象
			Statement stmt = conn.createStatement();
			//输入SQL语句操作数据库
            stmt.execute("UPDATE students SET sage = 40 WHERE NAME='王五';# sid = 2");
			/*//Statement风险:SQL注入
				     String id = "5 or 1=1";
		             String sql = "delete from demo where id ="+id;
		             stmt.execute(sql);
		             //通过输入恒等式执行execute,删除了所有的数据
             */
         
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException ex){
            ex.printStackTrace();
        }finally
        {   //关闭Statement
            try{
                if(stmt !=null) {
                    stmt.close();
                }
            }catch (SQLException se)
            {
                se.printStackTrace();
            }
            //关闭Connect
            try {
                if(conn!=null)
                {
                    conn.close();
                }
            }catch (SQLException e)
            {
                e.printStackTrace();
            }
        }
    }
}