1、Statement接口引入
作用:用于执行静态SQL语句并返回它所生成结果的对象。
int executeUpdate(String sql) :执行给定SQL语句,该语句可能为insert、update、或者delete语句,或者不返回任何
内容的SQL语句。
void close() :立即释放此Statement对象的数据库和JDBC资源,而不是等待该对象自动。
2、使用Statement接口实现添加的操作:
MysqlUtil dbUtil = new MysqlUtil(); String sql = "insert into emp2(name,salary,age) values('zhangsan',1000,22)"; Connection conn = dbUtil.getConnection(); Statement stmt = conn.createStatement(); int result = stmt.executeUpdate(sql); System.out.println("操作的结果:"+result+"条数据"); stmt.close(); conn.close();
类型二:
private static int addEmp(String name,double salary,int age) throws Exception{ Connection conn = dbUtil.getConnection(); String sql = "insert into emp2(name,salary,age) values ('"+name+"',"+salary+","+age+")"; Statement stmt = conn.createStatement(); System.out.println(sql); int result = stmt.executeUpdate(sql); dbUtil.close(stmt, conn); return result; } public static void main(String[] args) throws Exception{ int result = addEmp("lisi222",2000,23); System.out.println(result); if(result==1){ System.out.println("添加成功"); }else{ System.out.println("添加失败"); } }
3、使用Statement接口实现更新的操作:
public class JDBCDemo3 { private static MysqlUtil dbUtil = new MysqlUtil(); private static int updateEmp(Emp emp) throws Exception{ Connection conn = dbUtil.getConnection(); String sql = "update emp2 set name='"+emp.getName() +"',salary="+emp.getSalary() +" , age="+emp.getAge() +" where id=" +emp.getId(); Statement stmt = conn.createStatement(); System.out.println(sql); int result = stmt.executeUpdate(sql); dbUtil.close(stmt, conn); return result; } public static void main(String[] args) throws Exception{ Emp emp = new Emp(9,"lisi22",3210,33); int result = updateEmp(emp); if(result==1){ System.out.println("update成功"); }else{ System.out.println("update失败"); } } }
4、使用Statement接口实现删除的操作:
public class JDBCDemo4 { private static MysqlUtil dbUtil = new MysqlUtil(); /** * 删除emp * @param id * @return * @throws Exception */ private static int deleteEmp(int id) throws Exception{ Connection conn = dbUtil.getConnection(); String sql = "delete from emp2 where id="+id; Statement stmt = conn.createStatement(); System.out.println(sql); int result = stmt.executeUpdate(sql); dbUtil.close(stmt, conn); return result; } public static void main(String[] args) throws Exception{ int result = deleteEmp(9); if(result==1){ System.out.println("delete成功"); }else{ System.out.println("delete失败"); } } }