1, PreparedStatement interface Introduction
PreparedStatement is a statement sub-interface, which is a preprocessing operation, unlike the direct use of statement, PreparedStatement in operation,
is to first prepare an SQL statement in the datasheet, but the specifics of this SQL statement are not set for the time being, but are set later.
(later developed generally using PreparedStatement, without statement)
2. Add data operation using PreparedStatement interface
Public classJDBCDemo5 {Private StaticMysqlutil Dbutil =NewMysqlutil (); /*** Add EMP *@paramEMP *@return * @throwsException*/ Private Static intAddemp (EMP EMP)throwsexception{Connection Conn=dbutil.getconnection (); String SQL= "INSERT into EMP2 values (null,?,?,?)"; PreparedStatement pstmt=conn.preparestatement (SQL); Pstmt.setstring (1, Emp.getname ()); Pstmt.setdouble (2, Emp.getsalary ()); Pstmt.setint (3, Emp.getage ()); intresult =pstmt.executeupdate (); Dbutil.close (PSTMT, conn); returnresult; } Public Static voidMain (string[] args)throwsException {emp emp=NewEMP ("Pengpeng", 13000,27); intresult =addemp (EMP); if(result==1) {System.out.println ("Add Success"); }Else{System.out.println ("Add Failed"); } }}
3. Using the PreparedStatement interface for updating data operation
Public classJDBCDemo6 {Private StaticMysqlutil Dbutil =NewMysqlutil (); Private Static intUpdateemp (EMP EMP)throwsexception{Connection Conn=dbutil.getconnection (); String SQL= "Update emp2 set name=?,salary=?,age=?" where id=? "; PreparedStatement pstmt=conn.preparestatement (SQL); Pstmt.setstring (1, Emp.getname ()); Pstmt.setdouble (2, Emp.getsalary ()); Pstmt.setint (3, Emp.getage ()); Pstmt.setint (4, Emp.getid ()); intresult =pstmt.executeupdate (); Dbutil.close (PSTMT, conn); returnresult; } Public Static voidMain (string[] args)throwsException {emp emp=NewEMP (4, "Pengpeng", 13000,27); intresult =updateemp (EMP); if(result==1) {System.out.println ("Update succeeded"); }Else{System.out.println ("Update Failed"); } }}
4. Using PreparedStatement interface to implement delete data operation
Public classJDBCDemo7 {Private StaticMysqlutil Dbutil =NewMysqlutil (); Private Static intDeleteemp (intIdthrowsexception{Connection Conn=dbutil.getconnection (); String SQL= "Delete from emp2 where id=?"; PreparedStatement pstmt=conn.preparestatement (SQL); Pstmt.setint (1, id); intresult =pstmt.executeupdate (); Dbutil.close (PSTMT, conn); returnresult; } Public Static voidMain (string[] args)throwsexception{EMP EMP=NewEMP (4, "Pengpeng", 13000,27); intresult = Deleteemp (4); if(result==1) {System.out.println ("Delete Succeeded"); }Else{System.out.println ("Delete Failed"); } }}
JDBC (3)-Use the PreparedStatement interface for adding, deleting, and changing operations