Statement接口是用来执行SQL语句,通过连接对象的createStatement()方法获取语句对象。
1.Statement接口对象常用方法
Statement接口对象常用方法见下表: |方法名字|作用| |-|-| |public Statement createStatement()throws SQLException|通过连接对象创建语句对象| |public int executeUpdate()throws SQLException|执行更新语句,返回受影响的行数;| |public ResultSet executeQuery()throws SQLException|执行查询语句返回数据集| |public Statement execute()throws SQLException|可执行更新或者查询语句,返回boolean|
2.executeUpdate()
实例:
Connection conn = DBUtils.getConnection();
//1.执行更新语句
String sql = "insert into students (sname,gender) values('张飞','男')";
Statement stmt = conn.createStatement();
int result = stmt.executeUpdate(sql);
System.out.println("受影响的记录条数是:" + result);
运行结果:
受影响的记录条数是:1
注意:不要通过尝试通过result>0这样的语句作为判断更新语句是否更新成功的依据。例如:
Connection conn = DBUtils.getConnection();
//1.执行更新语句
String sql = "insert into students (sname,gender) values('小乔','女')";
Statement stmt = conn.createStatement();
int result = stmt.executeUpdate(sql);
if(result>0){
System.out.println("更新成功!");
}else{
System.out.println("更新失败!");
}
因为更新语句不仅仅只有插入,对于删除语句,如果删除一个编号不存在记录,返回受影响的条数为0,这样我们也不能认为该语句就是执行失败。通常的做法是使用try{}catch()包裹住要执行的更新语句,通过是否捕获到异常,来判断语句是否执行成功。例如:
Connection conn = null;
Statement stmt = null;
try {
conn = DBUtils.getConnection();
//1.执行更新语句
String sql = "insert into students (sname,gender) values('小乔','女')";
stmt = conn.createStatement();
int result = stmt.executeUpdate(sql);
System.out.println("更新成功!");
}catch(Exception ex){
ex.printStackTrace();
System.out.println("更新失败!");
}
finally {
//这里释放资源
}
3.executeQuery()
Connection conn = null;
Statement stmt = null;
String sql = "";
try {
conn = DBUtils.getConnection();
stmt = conn.createStatement();
//1.执行查询语句
sql = "select * from students where sid = 3";
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()){
System.out.println("学号:" + rs.getInt("sid") + "姓名:" + rs.getString("sname"));
}
}catch(Exception ex){
ex.printStackTrace();
}
finally {
//这里释放资源
}
4.execute()
execute()返回值为false说明是执行了更新语句,返回值为true说明是执行了查询语句。 实例:
Connection conn = null;
Statement stmt = null;
String sql = "";
try {
conn = DBUtils.getConnection();
stmt = conn.createStatement();
//1.执行查询语句
sql = "select * from students where sid = 3";
boolean flag = stmt.execute(sql);
if (flag) {
System.out.println("执行了查询语句");
} else {
System.out.println("执行了更新语句");
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
//这里释放资源
}
运行结果:
执行了查询语句
由于Statement不支持动态传参,因此存在SQL注入的风险。例如:
public static boolean usersLogin(String username,String password) throws Exception{
String sql = "select * from users where username= '"+username+"' and password ='"+password +"'";
Statement stmt = DBUtil.getConnetion().createStatement();
ResultSet rs = stmt.executeQuery(sql);
if(rs.next()){
return true;
}
return false;
}
public static void main(String[] args) throws Exception{
if(usersLogin("admin","654321' or '1=1")){
System.out.println("用户登录成功!");
}else{
System.out.println("用户登录失败,请检查您的用户名或者密码是否正确!");
}
}
上例中,usersLogin()方法无论传入任何账号都可以登录成功。