1 Inserting data
public boolean ChaRu3 (user user) {
Boolean flag=true;
Connection Conn=null;
PreparedStatement Ps=null; Creating PreparedStatement Objects
String sql= "INSERT into User (NAME,PWD) VALUES (?,?)"; The SQL statement no longer uses the concatenation method to write the SQL statement in the form of a placeholder question mark.
Conn=dbconnutil.getconn ();
try {
Ps=conn.preparestatement (SQL);
Ps.setstring (1, User.getname ()); Sets the value for the placeholder, which starts at 1, the first argument is the position of the placeholder, and the second parameter is the value of the placeholder.
int i=ps.executeupdate ();
if (i==0) {
Flag=false;
}
catch (SQLException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}finally{
Dbconnutil.closeall (NULL, PS, conn);
}
return flag;
}
2 Modifying data
public boolean XiuGai3 (user user) {
Boolean flag=true;
Connection Conn=null;
PreparedStatement Ps=null;
String sql= "Update user set pwd=?" where name=? ";
Conn=dbconnutil.getconn ();
try {
Ps=conn.preparestatement (SQL);
Ps.setstring (1, user.getpwd ());
Ps.setstring (2, User.getname ());
int i= ps.executeupdate ();
if (i==0) {
Flag=false;
}
catch (SQLException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}finally{
Dbconnutil.closeall (NULL, PS, conn);
}
return flag;
}
3 Deleting data
public boolean SHANCHU3 (int id) {
Boolean flag=true;
Connection Conn=null;
PreparedStatement Ps=null;
String sql= "Delete from user where id=?";
Conn=dbconnutil.getconn ();
try {
Ps=conn.preparestatement (SQL);
Ps.setint (1, id);
int i=ps.executeupdate ();
if (i==0) {
Flag=false;
}
catch (SQLException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}finally{
Dbconnutil.closeall (NULL, PS, conn);
}
return flag;
}
4 Viewing data
public list<user> ChaKan3 () {
list<user> list= new Arraylist<user > ();
Connection Conn=null;
PreparedStatement Ps=null;
ResultSet Rs=null;
String sql= "SELECT * from user";
Conn=dbconnutil.getconn ();
try {
ps=conn.preparestatement (SQL);
Rs=ps.executequery ();
while (Rs.next ()) {
User user= new User ();
User.setname (rs.getstring ("name"));
List.add (user);
}
catch (SQLException e) {
//TODO auto-generated catch block
E.printstack Trace ();
}finally{
Dbconnutil.closeall (RS, PS, conn);
}
return list;
}