Statement接口是JDBC的一部分,允许我们向数据库发送SQL查询和更新语句,并从数据库中获取结果。Statement接口有多个子接口和实现类,常用的有以下几种:
Statement:用于执行普通的SQL语句,不带有参数。
PreparedStatement:用于执行预编译的SQL语句,可以带有参数,防止SQL注入攻击。
CallableStatement:用于执行数据库存储过程。
1.Statement的作用:
使用:创建Statement
对象。Statement
对象通常与Connection
对象关联,通过Connection
对象的createStatement()
方法创建。
1.1执行sql语句;
1.2.executeQuery(sql):执行DQL语句;返回值Resultset结果集对象;
1.3.executeUpdate(sql):执行DDL、DML语句;DML返回值是受影响的行数,DDL返回值可能是是受影响的行数为0;
1.4. 获取执行sql的对象 :Statement stmt = conn.createStatement();
1.5.int count=stmt.executeUpdate(sql);
2.PreparedStatement:
创建PreparedStatement对象:
PreparedStatement preparedStatement=conn.PreparedStatement(sql);
2.1.执行sql并防止sql注入;
Statement接口是JDBC中执行SQL语句的关键接口之一。通过创建Statement对象,我们可以执行各种对数据库的操作。但为了提高安全性,执行SQL语句时使用PreparedStatement防止sql注入,尤其是涉及用户输入的情况下。