程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> JAVA綜合教程 >> jsp-2 簡單的servlet連接mysql數據庫 增刪改查,jsp-2mysql

jsp-2 簡單的servlet連接mysql數據庫 增刪改查,jsp-2mysql

編輯:JAVA綜合教程

jsp-2 簡單的servlet連接mysql數據庫 增刪改查,jsp-2mysql


連接mysql數據庫的操作 有增刪改查

用的包有

commons-lang3-3.5

mysql-connector-java-5.1.40-bin

但是實際上也就是

數據查詢和數據處理兩種

 所以對數據庫的操作DAO只有兩種方法

package com.javaweb.dao;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


import com.javaweb.utils.StringUtlis;
import com.javaweb.utils.DBUtlis;
import com.javaweb.utils.DateUtlis;

/*
 * 數據庫操作類
 * */
public class DBDao<T> {

    public <T> List<T> findAll(String sql,Class<T> clazz,List<Object> params)throws Exception{
         List<T> list = new ArrayList<T>();
         Connection conn=DBUtlis.getConnection();
         PreparedStatement pstmt = null;
         ResultSet rs = null;
         Field field=null;
         int index=1;
         try {
             pstmt = conn.prepareStatement(sql);
             if(params != null && !params.isEmpty()){  
                    for(int i=0; i<params.size(); i++){  
                        pstmt.setObject(index++, params.get(i));  
                    }  
                }  
              rs = pstmt.executeQuery();
            ResultSetMetaData metaData  = rs.getMetaData();
            int colsCount= metaData.getColumnCount();
            while(rs.next()){
                T obj=clazz.newInstance();
                 for(int i = 0; i<colsCount; i++){
                     String colsName = metaData.getColumnName(i+1);
                     Object colsValue = rs.getObject(colsName);
                     if(colsValue == null){  
                         colsValue = "";  
                      }
                     try{
                         field=clazz.getDeclaredField(StringUtlis.camelName(colsName));
                     }catch(NoSuchFieldException e){
                         Class clazz1=clazz.getSuperclass();
                         try{
                             field=clazz1.getDeclaredField(StringUtlis.camelName(colsName));
                         }catch(NoSuchFieldException n){
                            
                         }
                     }
                     if(field!=null){
                         field.setAccessible(true);
                         if(colsValue instanceof java.sql.Date){
                             field.set(obj, DateUtlis.getStrDate((Date)colsValue));
                         }else{
                             field.set(obj, colsValue);  
                         }
                     }
                 }
                 list.add(obj);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }  catch (SecurityException e) {
            e.printStackTrace();
        }finally{
            DBUtlis.close(conn, pstmt, rs);
        }
        return list;
     }

    public int execute(String sql, List<Object> params) {
        // TODO Auto-generated method stub
        int result = 0;
        Connection conn = null;
        PreparedStatement ps = null;
        int index=1;
        try {
            conn = DBUtlis.getConnection();
            ps = conn.prepareStatement(sql);
            if(params != null && !params.isEmpty()){  
                for(int i=0; i<params.size(); i++){  
                    ps.setObject(index++, params.get(i));  
                }  
            }  
            result = ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
            result = -1;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            DBUtlis.close(conn, ps, null);
        }
        return result;
    }
}

補:後來我才發現這玩意應該有高手寫到jar包裡面的.....

其實裡面的意思也不是數據查詢和數據操作

而是得到一個結果和多個結果的區別

對數據的Dao的處理

package com.javaweb.dao;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;

import com.javaweb.dao.DBDao;
import com.javaweb.bean.User;

public class UserDao {
    private DBDao dao=new DBDao();
    
    public List<User> findAll(){
        List<User> list=new ArrayList<User>();
        StringBuffer sql=new StringBuffer();
        sql.append(" select id,username,password ");
        sql.append(" from user ");
        try {
            list=dao.findAll(sql.toString(), User.class, null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    public int add(User User) {
        // TODO Auto-generated method stub
        if(User==null){
            return 0;
        }
        StringBuffer sql=new StringBuffer();
        sql.append(" insert into user(id,username,password) ");
        sql.append(" values(?,?,?) ");
        List<Object> params =new ArrayList<Object>();
        params.add(User.getId());
        params.add(User.getUsername());
        params.add(User.getPassword());
        return dao.execute(sql.toString(), params);
    }

    public int delete(User user) {
        // TODO Auto-generated method stub
        if(user==null){
            return 0;
        }
        StringBuffer sql=new StringBuffer();
        sql.append(" delete from user where id=?");
        List<Object> params =new ArrayList<Object>();
        params.add(user.getId());
        return dao.execute(sql.toString(), params);
    }

    public int update(User user) {
        // TODO Auto-generated method stub
        if(user==null){
            return 0;
        }
        List<Object> params =new ArrayList<Object>();
        StringBuffer sql=new StringBuffer();
        sql.append(" update user set ");
        if(StringUtils.isNoneBlank(user.getUsername())){
            sql.append(" username= ?, ");
            params.add(user.getUsername());
        }
        if(StringUtils.isNoneBlank(user.getPassword())){
            sql.append(" password= ?,");
            params.add(user.getPassword());
        }
        String strSql=sql.toString().substring(0, sql.toString().length()-1)+" where id=? ";
        params.add(user.getId());
        return dao.execute(strSql, params);
    }
}

User類

package com.javaweb.bean;

public class User {
    private String id;
    
    private String username;
    
    private String password;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }


}

servlet

package com.javaweb.action;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;

import com.javaweb.bean.User;
import com.javaweb.dao.UserDao;

public class ServletSql extends HttpServlet{

    /**
     * 用於版本控制
     */
    private static final long serialVersionUID = -2357925750878300415L;
    private UserDao dao=new UserDao();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // TODO Auto-generated method stub
        //純碎是用來判斷有沒有錯誤
        req.setCharacterEncoding("UTF-8");
        String op=req.getParameter("op");
        if(StringUtils.isNotBlank(op)){
            if("queryAll".equalsIgnoreCase(op)){
                queryAll(req, resp);
            }else if("add".equalsIgnoreCase(op)){
                add(req, resp);
            }else if("delete".equalsIgnoreCase(op)){
                delete(req, resp);
            }else if("update".equalsIgnoreCase(op)){
                update(req, resp);
            }else{
                
            }
        }
    }
    private void update(HttpServletRequest req, HttpServletResponse resp) {
        // TODO Auto-generated method stub
        User user;
        try {
            user = init(req,resp);
            user.setId(req.getParameter("id"));
            int rows=dao.update(user);
            if(rows>0){
                queryAll(req, resp);
            }
        } catch (ServletException|IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 
    }

    private void delete(HttpServletRequest req, HttpServletResponse resp) {
        // TODO Auto-generated method stub
        User user=new User();
        String id=req.getParameter("id");
        user.setId(id);
        int rows=dao.delete(user);
        if(rows>0){
            try {
                queryAll(req, resp);
            } catch (ServletException|IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } 
        }
    }

    public User init(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        User user=new User();
        String id=req.getParameter("id");
//        user.setId(Integer.parseInt(id));
        user.setId(id);
        String name=req.getParameter("name");
        user.setUsername(name);
        String password=req.getParameter("password");
//        user.setPassword(Integer.parseInt(password));
        user.setPassword(password);
        return user;
    }
    public void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        User User=init(req,resp);
        int rows=dao.add(User);
        if(rows>0){
            queryAll(req, resp);
        }else{
            resp.sendRedirect("index.jsp");
        }
    }
    public void queryAll(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<User> list=dao.findAll();
        req.setAttribute("list", list);
        req.getRequestDispatcher("/queryAll.jsp").forward(req, resp);
//        resp.sendRedirect("queryAll.jsp");
    }
}

有幾個方法後接throws ServletException, IOException應該會更加的整潔

.properties文件

#\u6570\u636e\u8fde\u63a5\u914d\u7f6e
db.driver=com.mysql.jdbc.Driver
db.url=jdbc:mysql://localhost:3306/javaweb
db.userName=root
db.password=123456789

DateUtils

package com.javaweb.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateUtlis {

    /**
     * 獲取當前日期
     * @return
     */
    public static String getCurrentTime() {  
        String returnStr = null;  
        SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
        Date date = new Date();  
        returnStr = f.format(date);  
        return returnStr;  
    }  
    
    public static Date getDate(String strDate){
        Date date=null;
         SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd"); 
         try {
             date = f.parse(strDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
         return date;
    }
    
    public static String getStrDate(Date date){
         String strDate=null;
         SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd"); 
         strDate = f.format(date);
         return strDate;
    }
}

DButils

package com.javaweb.utils;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * 數據庫連接類
 * @author SUMMER
 *
 */
public class DBUtlis {
    
    private static String driver;
    private static String url;
    private static String userName;
    private static String password;
    
    static{
        driver=PropertiesUtil.getProperty("db.driver");
        url=PropertiesUtil.getProperty("db.url");
        userName=PropertiesUtil.getProperty("db.userName");
        password=PropertiesUtil.getProperty("db.password");
    }
    
    /**
     * 創建數據庫連接
     * @return
     */
    public static Connection getConnection() {
        Connection conn = null;
        try {
            Class.forName(driver);
            conn = java.sql.DriverManager.getConnection(url,userName, password);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return conn;
    }
    
    public static void close(Connection conn, PreparedStatement psm,ResultSet rs) {
        close(rs);
        close(psm);
        close(conn);
    }
    
    public static void close(Connection conn, Statement st,ResultSet rs) {
        close(rs);
        close(st);
        close(conn);
    }
    
    public static void close(Connection conn, PreparedStatement psm) {
        close(psm);
        close(conn);
    }
    
    public static void close(Connection conn) {
        if (null != conn) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    
    public static void close(ResultSet rs) {
        if (null != rs) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    
    public static void close(PreparedStatement psm) {
        if (null != psm) {
            try {
                psm.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    
    public static void close(CallableStatement proc) {
        if (null != proc) {
            try {
                proc.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    
    /**
     * @param st
     */
    public static void close(Statement st) {
        if (null != st) {
            try {
                st.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    
    /**
     * @param conn
     */
    public static void rollback(Connection conn) {
        if(conn != null) {
            try {
                conn.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
        }
    }
    
    /**
     * @param conn
     * @param auto
     */
    public static void setAutoCommit(Connection conn, boolean auto) {
        if(conn != null) {
            try {
                conn.setAutoCommit(auto);
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
        }
    }
    
    public static void main(String[] args) {
        DBUtlis.getConnection();
    }
}

propertiesUtils

package com.javaweb.utils;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * 讀取properties文件
 * @author SUMMER
 *
 */
public class PropertiesUtil {
    
    private static Properties prop;
    
    /**
     * 加載.properties文件,使用文件流
     */
    private static void init() {
        prop = new Properties();
        InputStream is=PropertiesUtil.class.getResourceAsStream("/config/db.properties");
        try {
            prop.load(is);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 獲取value
     * @param key
     * @return
     */
    public static String getProperty(String key) {
        if (prop == null ) {
            init();
        }
        return prop.get(key).toString();
    }
    
    public static void main(String[] args) {
        System.out.println(getProperty("db.driver"));
    }
}

StringUtils

package com.javaweb.utils;

import java.util.UUID;

/**
 * 字符串處理工具類
 *
 */
public class StringUtlis {

    /**
     * 獲取唯一ID
     * @return
     */
    public static String getUUID() {  
        UUID uuid = UUID.randomUUID(); 
        String str = uuid.toString();  
        return str.replace("-", "");  
    }  
    
    /**
     * 將駝峰式命名的字符串轉換為下劃線大寫方式。如果轉換前的駝峰式命名的字符串為空,則返回空字符串。</br>
     * 例如:HelloWorld->HELLO_WORLD
     * @param name 轉換前的駝峰式命名的字符串
     * @return 轉換後下劃線大寫方式命名的字符串
     */
    public static String underscoreName(String name) {
        StringBuilder result = new StringBuilder();
        if (name != null && name.length() > 0) {
            // 將第一個字符處理成大寫
            result.append(name.substring(0, 1).toUpperCase());
            // 循環處理其余字符
            for (int i = 1; i < name.length(); i++) {
                String s = name.substring(i, i + 1);
                // 在大寫字母前添加下劃線
                if (s.equals(s.toUpperCase()) && !Character.isDigit(s.charAt(0))) {
                    result.append("_");
                }
                // 其他字符直接轉成大寫
                result.append(s.toUpperCase());
            }
        }
        return result.toString();
    }
     
    /**
     * 將下劃線大寫方式命名的字符串轉換為駝峰式。如果轉換前的下劃線大寫方式命名的字符串為空,則返回空字符串。</br>
     * 例如:HELLO_WORLD->HelloWorld
     * @param name 轉換前的下劃線大寫方式命名的字符串
     * @return 轉換後的駝峰式命名的字符串
     */
    public static String camelName(String name) {
        StringBuilder result = new StringBuilder();
        // 快速檢查
        if (name == null || name.isEmpty()) {
            // 沒必要轉換
            return "";
        } else if (!name.contains("_")) {
            // 不含下劃線,僅將首字母小寫
            return name.substring(0, 1).toLowerCase() + name.substring(1);
        }
        // 用下劃線將原始字符串分割
        String camels[] = name.split("_");
        for (String camel :  camels) {
            // 跳過原始字符串中開頭、結尾的下換線或雙重下劃線
            if (camel.isEmpty()) {
                continue;
            }
            // 處理真正的駝峰片段
            if (result.length() == 0) {
                // 第一個駝峰片段,全部字母都小寫
                result.append(camel.toLowerCase());
            } else {
                // 其他的駝峰片段,首字母大寫
                result.append(camel.substring(0, 1).toUpperCase());
                result.append(camel.substring(1).toLowerCase());
            }
        }
        return result.toString();
    }
    
    
    public static void main(String[] args) {
        System.out.println(getUUID());
    }
    
}

utils就是工具類了

拿來就用,大多數情況下都有很多高手寫jar包含他們

但是我沒用那些jar直接上網找的

要求分門別類寫,是個好習慣

index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
    String path = request.getContextPath();// 獲得當前的項目根目錄路徑
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path;
    //完整路徑
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>這是首頁</title>
</head>
<body>
    <table border=0 cellpadding=0 cellspacing=0 ><%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%
    String path = request.getContextPath();// 獲得當前的項目根目錄路徑
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path;
    //完整路徑
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="<%=basePath%>/servletSql?op=add" method="post">
    <table align="center" border="1">
        <tr>
            <th colspan="3">
                <label>添加信息</label>
            </th>
        </tr>
        <tr>
            <td>Id</td>
            <td>
                <input type="text" name="id"  >
            </td>
        </tr>
        <tr>
            <td>用戶名</td>
            <td>
                <input type="text" name="name"  >
            </td>
        </tr>
        <tr>
            <td>密碼</td>
            <td>
                <input type="text" name="password"  >
            </td>
        </tr>
        <tr>
            <td>
            </td>
            <td>
                <input type="submit" value="保存">
                <input type="reset" value="清空">
            </td>
        </tr>
    </table>
</form>
</body>
</html>

delete

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%
    String path = request.getContextPath();// 獲得當前的項目根目錄路徑
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path;
    //完整路徑
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="<%=basePath%>/servletSql?op=delete" method="post">
    <table align="center" border="1">
        <tr>
            <th colspan="3">
                <label>刪除信息</label>
            </th>
        </tr>
        <tr>
            <td>Id</td>
            <td>
                <input type="text" name="id"  >
            </td>
        </tr>
        <tr>
            <td>
            </td>
            <td>
                <input type="submit" value="保存">
                <input type="reset" value="清空">
            </td>
        </tr>
    </table>
</form>
</body>
</html>

queryAll

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%
    String path = request.getContextPath();// 獲得當前的項目根目錄路徑
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path;
    //完整路徑
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="<%=basePath%>/servletSql?op=delete" method="post">
    <table align="center" border="1">
        <tr>
            <th colspan="3">
                <label>刪除信息</label>
            </th>
        </tr>
        <tr>
            <td>Id</td>
            <td>
                <input type="text" name="id"  >
            </td>
        </tr>
        <tr>
            <td>
            </td>
            <td>
                <input type="submit" value="保存">
                <input type="reset" value="清空">
            </td>
        </tr>
    </table>
</form>
</body>
</html>

 

update

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%
    String path = request.getContextPath();// 獲得當前的項目根目錄路徑
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path;
    //完整路徑
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="<%=basePath%>/servletSql?op=update" method="post">
    <table align="center" border="1">
        <tr>
            <th colspan="3">
                <label>修改信息</label>
            </th>
        </tr>
        <tr>
            <td>Id</td>
            <td>
                <input type="text" name="id"  >
            </td>
        </tr>
        <tr>
            <td>用戶名</td>
            <td>
                <input type="text" name="name"  >
            </td>
        </tr>
        <tr>
            <td>密碼</td>
            <td>
                <input type="text" name="password"  >
            </td>
        </tr>
        <tr>
            <td>
            </td>
            <td>
                <input type="submit" value="保存">
                <input type="reset" value="清空">
            </td>
        </tr>
    </table>
</form>
</body>
</html>

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved