java web 向mysql数据库添加记录和取出所有信息。通过代码处理自动增长的id

发布时间:2024年01月20日

java web 向mysql数据库添加记录和取出所有信息。通过代码处理自动增长的id

?

CREATE DATABASE IF NOT EXISTS contactDB; -- 如果不存在 contactDB 数据库,则创建该数据库

USE contactDB; -- 进入 contactDB 数据库

CREATE TABLE IF NOT EXISTS contact ( -- 如果不存在 contact 表,则创建该表
    Cid VARCHAR(8) PRIMARY KEY,
    cname VARCHAR(20),
    phone VARCHAR(20),
    Address VARCHAR(20),
    email VARCHAR(20)
);
<%@page import="biz.ContactsBizImp"%>
<%@page import="java.util.List"%>
<%@page import="entity.*"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    
    <%
    ContactsBizImp cbi = new ContactsBizImp();
    List<Contacts> list= cbi.allContacts();
    
    %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>我的通讯录</title>
<style type="text/css">
h1{
text-align: center;
}
table{
width:100%;
text-align: center;
}
</style>
</head>
<body>
<!-- 显示所有记录 -->
<h1>添加新联系人</h1>
<hr>

<table>
 <!-- 表头内容 -->
	<thead>
	    <tr>
	      <th>序号</th>
	      <th>联系人</th>
	      <th>联系地址</th>
	      <th>联系电话</th>
	      <th>Email</th>
	    </tr>
	  </thead>
	  
   <!-- 表格内容 -->
   <%for(Contacts c:list){%>
   
   <tr>
      <td><%=c.getCid() %></td>      
      <td><%=c.getCname() %></td>
      <td><%=c.getAddress() %></td>
      <td><%=c.getPhone() %></td>
      <td><%=c.getEmail() %></td>
    </tr>
   
   <%}%>
   


</table>
</body>
</html>

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>添加联系人</title>

 <script>
        function validateForm() {
            var contact = document.getElementById("contact").value;
            var address = document.getElementById("address").value;
            var phone = document.getElementById("phone").value;
            var email = document.getElementById("email").value;

            if (contact.trim() == '') {
                alert("请输入联系人!");
                return false;
            }
            if (address.trim() == '') {
                alert("请输入地址!");
                return false;
            }
            if (phone.trim() == '') {
                alert("请输入电话!");
                return false;
            }
            if (email.trim() == '') {
                alert("请输入E-mail!");
                return false;
            }

            return true;
        }
    </script>
    
</head>
<body>
<form action="add" method="POST">
        <label for="contact">联系人:</label>
        <input type="text" id="contact" name="contact" required>联系人姓名不能为空<br>

        <label for="address">地&nbsp;&nbsp;&nbsp;址:</label>
        <input type="text" id="address" name="address" required>地址不能为空<br>

        <label for="phone">电&nbsp;&nbsp;&nbsp;话:</label>
        <input type="tel" id="phone" name="phone" required>电话不能为空<br>

        <label for="email">E-mail:</label>
        <input type="email" id="email" name="email" required>Email不能为空<br>

        <input type="submit" value="添加联系人">
    </form>
</body>
</html>
package entity;

public class Contacts {
	private String Cid,cname,phone,Address,email;

	public String getCid() {
		return Cid;
	}

	public void setCid(String cid) {
		Cid = cid;
	}

	public String getCname() {
		return cname;
	}

	public void setCname(String cname) {
		this.cname = cname;
	}

	public String getPhone() {
		return phone;
	}

	public void setPhone(String phone) {
		this.phone = phone;
	}

	public String getAddress() {
		return Address;
	}

	public void setAddress(String address) {
		Address = address;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}
	
	

}



import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import biz.ContactsBizImp;
import entity.Contacts;

/**
 * Servlet implementation class Add
 */
@WebServlet({ "/Add", "/add" })
public class Add extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Add() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//response.getWriter().append("Served at: ").append(request.getContextPath());
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		
		//接收数据 4个字符串变量
		String contact=request.getParameter("contact");
		String address=request.getParameter("address");
		String phone=request.getParameter("phone");
		String email=request.getParameter("email");
		
		if(contact==null || address==null || phone==null || email==null) {
			response.getWriter().append("Error~!!");
			return ;
		}
		ContactsBizImp cbi = new ContactsBizImp();
		String cid;
		try {
			cid=cbi.getNewtId();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return; 
		}
		
		Contacts c= new Contacts();
		c.setCid(cid);
		c.setAddress(address);
		c.setCname(contact);
		c.setEmail(email);
		c.setPhone(phone);
		
		try {
			cbi.addContacts(c);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return ;
		}
		response.sendRedirect("index.jsp");
		return ;
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

package util;
import java.sql.*;
public class BaseDao {
	    public final static String driver = "com.mysql.cj.jdbc.Driver";                     // 数据库驱动
	    public final static String url    = "jdbc:mysql://121.41.116.214:3306/contactDB";   // url
	    public final static String dbName = "contactdb";                                                               // 数据库用户名
	    public final static String dbPass = "Uqbxvy61V3gaFLpz";                                                               // 数据库密码	    
	
 
	    public static Connection getConn() throws ClassNotFoundException, SQLException{
	        Class.forName(driver);                                     //注册驱动
	        return DriverManager .getConnection(url,dbName,dbPass);   //获得数据库连接并返回
	    }
	    
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          
	    public static void closeAll( Connection conn, PreparedStatement pstmt, ResultSet rs ) {
	        /*  如果rs不空,关闭rs  */
	        if(rs != null){
	            try { rs.close();} catch (SQLException e) {e.printStackTrace();}
	        }
	        /*  如果pstmt不空,关闭pstmt  */
	        if(pstmt != null){
	            try { pstmt.close();} catch (SQLException e) {e.printStackTrace();}
	        }
	        /*  如果conn不空,关闭conn  */
	        if(conn != null){
	            try { conn.close();} catch (SQLException e) {e.printStackTrace();}
	        }
	    }
	    public static int executeSQL(String sql,String[] param) {
	        Connection        conn  = null;
	        PreparedStatement pstmt = null;
	        int               num   = 0;
	        
	        /*  处理SQL,执行SQL  */
	        try {
	            conn = getConn();                              // 得到数据库连接
	            pstmt = conn.prepareStatement(sql);    // 得到PreparedStatement对象
	            if( param != null ) {
	                for( int i = 0; i < param.length; i++ ) {
	                    pstmt.setString(i+1, param[i]);         // 为预编译sql设置参数
	                }
	            }
	            num = pstmt.executeUpdate();                    // 执行SQL语句
	        } catch (ClassNotFoundException e) {
	            e.printStackTrace();                            // 处理ClassNotFoundException异常
	        } catch (SQLException e) {
	            e.printStackTrace();                            // 处理SQLException异常
	        } finally {
	            closeAll(conn,pstmt,null);                     // 释放资源
	        }
	        return num;
	    }
}
package dao;

import java.util.List;

import entity.Contacts;

//打算有哪些功能
public interface IContactsDao {	
	public List<Contacts> allContacts() throws Exception;
	public int addContacts(Contacts contact) throws Exception;	
}

package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.LinkedList;
import java.util.List;

import entity.Contacts;
import util.BaseDao;




public class ContactsDaoImp implements IContactsDao {
	private Connection conn=null;
	private PreparedStatement pstmt=null;
	ResultSet rs=null;
	@Override
	public List<Contacts> allContacts() throws Exception {
		// TODO Auto-generated method stub
		List<Contacts> list=new LinkedList<Contacts>();
		String sql="SELECT * FROM contact";
		conn = BaseDao.getConn();
		pstmt=conn.prepareStatement(sql);
		rs=pstmt.executeQuery();
		while(rs.next()) {
			Contacts contacts = new Contacts();
			contacts.setCid(rs.getString(1));			
			contacts.setCname(rs.getString(2));
			contacts.setPhone(rs.getString(3));
			contacts.setAddress(rs.getString(4));
			contacts.setEmail(rs.getString(5));			
			list.add(contacts);
		}
		BaseDao.closeAll(conn,pstmt,rs);
		return list;
 
	}

	@Override
	public int addContacts(Contacts contact) throws Exception {
		// TODO Auto-generated method stub
		conn = BaseDao.getConn();		
		String sql="INSERT INTO contact (Cid, cname, phone, Address,email) VALUES (?,?,?,?,?)";
		String[] param = {contact.getCid(),contact.getCname(),contact.getPhone(),contact.getAddress(),contact.getEmail()};
		System.out.println(contact.getCid()+contact.getCname()+contact.getPhone()+contact.getAddress()+contact.getEmail());
		int row = BaseDao.executeSQL(sql, param);
		BaseDao.closeAll(conn,pstmt,null);
		return row;		
	}
	 
}

package biz;

import java.util.List;

import entity.Contacts;

//打算有哪些功能
public interface IContactsBiz {	
	public List<Contacts> allContacts() throws Exception;
	public int addContacts(Contacts contact) throws Exception;
	public String getNewtId() throws Exception;
}

package biz;


import java.util.LinkedList;
import java.util.List;

import dao.ContactsDaoImp;
import dao.IContactsDao;
import entity.Contacts;

public class ContactsBizImp implements IContactsBiz {
	IContactsDao ic = null; 
	
	public ContactsBizImp() {
		ic =  new ContactsDaoImp();
	}

	@Override
	public List<Contacts> allContacts() throws Exception {
		// TODO Auto-generated method stub
		return ic.allContacts();
	}

	@Override
	public int addContacts(Contacts contact) throws Exception {
		// TODO Auto-generated method stub
		return ic.addContacts(contact);
	}

	@Override
	public String getNewtId() throws Exception {
		// TODO Auto-generated method stub
		LinkedList<Contacts> list=(LinkedList<Contacts>)ic.allContacts();
		if(list==null)
			return ""+1;
		
		String cid = list.getLast().getCid();
		
		return "" + (Integer.parseInt(cid)+1);
	}

 
	 
}

文章来源:https://blog.csdn.net/laocooon/article/details/135715474
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。