Statement简介

Statement接口特点
用于执行静态 SQL 语句并返回它所生成结果的对象。 由 createStatement 创建,用于发送简单的 SQL 语句(不支持动态绑定)。

注意:由于Statement对象是一个执行静态SQL语句的对象,所以该对象存在SQL注入风险。

JDBC中三种Statement对象

  • Statement:用于执行静态 SQL 语句。
  • PreparedStatement:用于执行预编译SQL语句。
  • CallableStatement:用于执行数据库存储过程。

image.png

添加数据

创建表:
CREATE TABLE users (
userid int(11) NOT NULL AUTO_INCREMENT,
username varchar(30) DEFAULT NULL,
userage int(11) DEFAULT NULL,
PRIMARY KEY (userid)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

  1. import java.sql.Connection;
  2. import java.sql.Statement;
  3. public class StatementTest {
  4. //添加用户
  5. public void insetUsers(String username,int userage){
  6. Connection connection = null;
  7. Statement statement = null;
  8. try {
  9. //获取Connection对象
  10. connection = JDBCUtils.getConnection();
  11. //获取Statement对象
  12. statement = connection.createStatement();
  13. //定义需要执行的语句
  14. String sql ="insert into users values(default,'"+username+"',"+userage+")";
  15. //执行sql语句,返回布尔值,如果sql有结果集返回,那么返回值为true
  16. boolean execute = statement.execute(sql);
  17. System.out.println(execute);
  18. }catch (Exception e){
  19. e.printStackTrace();
  20. }finally {
  21. JDBCUtils.clossResource(statement,connection);
  22. }
  23. }
  24. }
  1. public class Test {
  2. public static void main(String[] args) {
  3. StatementTest statementTest = new StatementTest();
  4. statementTest.insetUsers("laogeng", 25);
  5. }
  6. }

image.png

更新数据

  1. /**
  2. * 更新数据
  3. */
  4. public void updateUsers(int userid,String username,int userage){
  5. Connection connection = null;
  6. Statement statement = null;
  7. try {
  8. connection = JDBCUtils.getConnection();
  9. statement = connection.createStatement();
  10. String sql = "update users set username='"+username+"',userage="+userage+" where userid="+userid;
  11. int i=statement.executeUpdate(sql);
  12. System.out.println(i);
  13. }catch (Exception e){
  14. e.printStackTrace();
  15. }finally {
  16. JDBCUtils.clossResource(statement,connection);
  17. }
  18. }

删除数据

  1. /**
  2. * 根据userid删除数据
  3. */
  4. public void deleteUsersById(int userid){
  5. Connection connection = null;
  6. Statement statement = null;
  7. try {
  8. connection = JDBCUtils.getConnection();
  9. statement= connection.createStatement();
  10. String sql ="delete from users where userid="+userid;
  11. int i = statement.executeUpdate(sql);
  12. System.out.println(i);
  13. }catch (Exception e){
  14. e.printStackTrace();
  15. }finally {
  16. JDBCUtils.clossResource(statement,connection);
  17. }
  18. }