Statement简介
Statement接口特点
用于执行静态 SQL 语句并返回它所生成结果的对象。 由 createStatement 创建,用于发送简单的 SQL 语句(不支持动态绑定)。
注意:由于Statement对象是一个执行静态SQL语句的对象,所以该对象存在SQL注入风险。
JDBC中三种Statement对象
- Statement:用于执行静态 SQL 语句。
- PreparedStatement:用于执行预编译SQL语句。
- CallableStatement:用于执行数据库存储过程。

添加数据
创建表:
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;
import java.sql.Connection;import java.sql.Statement;public class StatementTest {//添加用户public void insetUsers(String username,int userage){Connection connection = null;Statement statement = null;try {//获取Connection对象connection = JDBCUtils.getConnection();//获取Statement对象statement = connection.createStatement();//定义需要执行的语句String sql ="insert into users values(default,'"+username+"',"+userage+")";//执行sql语句,返回布尔值,如果sql有结果集返回,那么返回值为trueboolean execute = statement.execute(sql);System.out.println(execute);}catch (Exception e){e.printStackTrace();}finally {JDBCUtils.clossResource(statement,connection);}}}
public class Test {public static void main(String[] args) {StatementTest statementTest = new StatementTest();statementTest.insetUsers("laogeng", 25);}}

更新数据
/*** 更新数据*/public void updateUsers(int userid,String username,int userage){Connection connection = null;Statement statement = null;try {connection = JDBCUtils.getConnection();statement = connection.createStatement();String sql = "update users set username='"+username+"',userage="+userage+" where userid="+userid;int i=statement.executeUpdate(sql);System.out.println(i);}catch (Exception e){e.printStackTrace();}finally {JDBCUtils.clossResource(statement,connection);}}
删除数据
/*** 根据userid删除数据*/public void deleteUsersById(int userid){Connection connection = null;Statement statement = null;try {connection = JDBCUtils.getConnection();statement= connection.createStatement();String sql ="delete from users where userid="+userid;int i = statement.executeUpdate(sql);System.out.println(i);}catch (Exception e){e.printStackTrace();}finally {JDBCUtils.clossResource(statement,connection);}}
