servlet
package demo;
import java.sql.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class JDBC {
public Connection connect() throws ClassNotFoundException, SQLException{
? ? Connection conn=null;?
? ? Class.forName("com.mysql.jdbc.Driver");
? ? String url = "jdbc:mysql://47.122.1.22/pzj_users?"
? ? ? ? ? ? ? ? + "user=root_user&password=pzj2020@&useUnicode=true&characterEncoding=UTF8";
conn=DriverManager.getConnection(url);?
return conn;
}
public void close(Statement stat,Connection conn) throws SQLException{
if(stat!=null){
? ? ? ?stat.close();
? ? }
? ? if(conn!=null){
? ? ? ?conn.close();? ? ?
? ? }
}
public int insert(HttpServletRequest request, HttpServletResponse response) throws ClassNotFoundException, SQLException{
? ? Connection conn=null;
? ? Statement stat=null;
? ? ? ? String name=request.getParameter("name");
? ? ? ? String password=request.getParameter("password");? ??
conn=connect();
stat=conn.createStatement();
int i=stat.executeUpdate("insert into shule_user values('"+name+"','"+password+"')");?
? ? close(stat,conn);
? ? return i;
? ? }
public int delete(HttpServletRequest request, HttpServletResponse response) throws ClassNotFoundException, SQLException{
? ? Connection conn=null;
? ? Statement stat=null;
? ? ? ? String name=request.getParameter("name");
conn=connect();
stat=conn.createStatement();
int i=stat.executeUpdate("delete from shule_user where name ='"+name+"'");
? ? close(stat,conn);
? ? return i;
? ? }
public int change(HttpServletRequest request, HttpServletResponse response) throws ClassNotFoundException, SQLException{
? ? Connection conn=null;
? ? Statement stat=null;
? ? ? ? String name=request.getParameter("name");
? ? ? ? String password=request.getParameter("password");
conn=connect();
stat=conn.createStatement();
int i=stat.executeUpdate("update shule_user set password='"+password+"' where name ='"+name+"'");
? ? close(stat,conn);
? ? return i;
? ? }
public String view(HttpServletRequest request, HttpServletResponse response) throws ClassNotFoundException, SQLException{
? ? Connection conn=null;
? ? Statement stat=null;
? ? ResultSet rs=null;
? ? conn=connect();
stat=conn.createStatement();
? ? String Data="";
? ? ? ? ?rs=stat.executeQuery("select * from shule_user");?
? ? while(rs.next())
? ? ? ? {
? ? Data+=rs.getString("name")+" "+rs.getString("password")+" "+"\n";
? ? ? ? }
? ? if(rs!=null){
? ? ? rs.close();
? ? ? ?}
? ? close(stat,conn);
? ? return Data;
? ? }
}