1 Inserting data
public boolean ChaRu3 (user user) {
Boolean flag=true;
Connection Conn=null;
PreparedStatement Ps=null; Create a PreparedStatement object
String sql= "INSERT into User (NAME,PWD) VALUES (?,?)"; SQL statements no longer use stitching, and the placeholder question mark is used to write SQL statements.
Conn=dbconnutil.getconn ();
try {
Ps=conn.preparestatement (SQL);
Ps.setstring (1, User.getname ()); Set the value for the placeholder, which starts at 1, the first parameter is the position of the placeholder, and the second parameter is the value of a placeholder.
Ps.setstring (2, User.getpwd ());
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.printstacktrace ();
}finally{
Dbconnutil.closeall (RS, PS, conn);
}
return list;
}
JDBC Note 3 The database is PreparedStatement and censored through the