Java-JDBC与java数据库编程-基于MVC三层编程_小项目示例代码

涎涎原创约 3728 字大约 12 分钟...JavaJava

258-J76-Java-JDBC与java数据库编程-基于MVC三层编程_小项目示例代码.md.md

注意

本博文仅供学术研究和交流参考,严禁将其用于商业用途。如因违规使用产生的任何法律问题,使用者需自行负责。

概念

示例代码

  1. config
#\u672C\u673A\u73AF\u5883
jdbc.driverClassName =  oracle.jdbc.driver.OracleDriver
jdbc.url = jdbc:oracle:thin:@localhost:1521:orcl
jdbc.username = scott
jdbc.password = scott123

#\u8FDC\u7A0B\u73AF\u5883
#jdbc.driverClassName =  oracle.jdbc.driver.OracleDriver
#jdbc.url = jdbc:oracle:thin:@10.25.160.66:1521:orcl
#jdbc.username = scott
#jdbc.password = scott123

#-------------------------------------------------------
#mysql   
#jdbc.driverClassName =  com.mysql.jdbc.Driver
#jdbc.url = jdbc:mysql://localhost:3306/ems
#jdbc.username = root
#jdbc.password = 123456
  1. dao
package com.tencent.dao;

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

import com.tencent.entity.Emp;
import com.tencent.util.DBUtil;

public class BonusDaoImpl implements IBonusDao {

	private Connection conn = null;
	private PreparedStatement stat = null;
	private ResultSet rs = null;

	@Override
	public boolean insertBonus(Emp emp) {
		try {
			//1~3 获取数据库连接
			conn = DBUtil.getConnection();
			
			//4.创建PreparedStatement对象
			stat = conn.prepareStatement("insert into bonus (ename, job, sal, comm) values (?, ?, ?, ?)");

			//4.1绑定变量值
			stat.setString(1, emp.getEname());
			stat.setString(2, emp.getJob());
			stat.setDouble(3, emp.getSalary());
			stat.setDouble(4, emp.getComm());
			//5.执行查询或更新
			int result = stat.executeUpdate();
			
			//6.结果处理
			if(result > 0)
			{
				return true;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			//7.关闭连接
			DBUtil.close(conn, stat, rs);
		}
		
		return false;
	}
}
package com.tencent.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.tencent.entity.Emp;
import com.tencent.util.DBUtil;

public class EmpDaoImpl implements IEmpDao {

	private Connection conn = null;
	private PreparedStatement stat = null;
	private ResultSet rs = null;
	
	@Override
	public List<Emp> selectEmps() {
		try {
			//1~3 获取数据库连接
			conn = DBUtil.getConnection();
			
			//4.创建PreparedStatement对象
			stat = conn.prepareStatement("select empno, ename empName, job, mgr, hiredate, sal, comm, deptno from emp");

			//5.执行查询或更新
			rs = stat.executeQuery();
			
			//6.结果处理
			List<Emp> empList = new ArrayList<Emp>();
			while(rs.next())
			{
				//每遍历一次,获得一个Emp的员工信息
				Emp emp = new Emp();
				emp.setEmpno(rs.getInt("empno"));
				emp.setEname(rs.getString("empName"));
				emp.setJob(rs.getString("job"));
				emp.setManager(rs.getInt("mgr"));
				
				/**
				 * java.sql.Date(子类) -> java.util.Date(父类):子类自动转换为父类
				 * java.sql.Time(子类) -> java.util.Date(父类):子类自动转换为父类
				 * java.sql.Timestamp(子类) -> java.util.Date(父类):子类自动转换为父类
				 * 
				 * java.sql.Date:表示年月日
				 * java.sql.Time:表示时分秒
				 * java.sql.Timestamp:表示年月日时分秒
				 */
				//emp.setHiredate(rs.getDate("hiredate"));     //Date  2019-09-16
				//emp.setHiredate(rs.getTimestamp("hiredate"));//Timestamp  2019-09-16 15:49:49.0
				emp.setHiredate(rs.getTime("hiredate"));       //Time  15:49:49
				
				emp.setSalary(rs.getDouble("sal"));
				emp.setComm(rs.getDouble("comm"));
				emp.setDeptno(rs.getInt("deptno"));
				
				//将当前的emp添加到集合
				empList.add(emp);
			}
			return empList;
			
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			//7.关闭连接
			DBUtil.close(conn, stat, rs);
		}
		
		return null;
	}

	@Override
	public boolean insertEmp(Emp emp) {
		try {
			//1~3 获取数据库连接
			conn = DBUtil.getConnection();
			
			//4.创建PreparedStatement对象
			// 使用序列完成主键自增:create sequence seq_emp;
			stat = conn.prepareStatement("insert into emp(empno,ename,job,hiredate) values(seq_emp.nextval,?,?,?)");

			//4.1绑定变量值
			//stat.setInt(1, emp.getEmpno());
			stat.setString(1, emp.getEname());
			stat.setString(2, emp.getJob());
			
			/**
			 * java.util.Date(父类)  -> java.sql.Date(子类):
			 * 	
			 * 		① 将java.util.Date(父类) -> 毫秒值
			 * 			long milliSeconds = emp.getHiredate().getTime();
			 * 
			 *		② 毫秒值 -> java.sql.Date(子类)
			 *			java.sql.Date date = new java.sql.Date(milliSeconds);
			 *			java.sql.Time date = new java.sql.Time(milliSeconds);
			 *			java.sql.Timestamp date = new java.sql.Timestamp(milliSeconds);
			 * 			
			 */
			stat.setDate(3, new java.sql.Date(emp.getHiredate().getTime()));
			//stat.setTime(3, new java.sql.Time(emp.getHiredate().getTime()));
			//stat.setTimestamp(3, new java.sql.Timestamp(emp.getHiredate().getTime()));
			
			//5.执行查询或更新
			int result = stat.executeUpdate();
			
			//6.结果处理
			if(result > 0)
			{
				return true;
			}
			
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			//7.关闭连接
			DBUtil.close(conn, stat, rs);
		}
		
		return false;
	}

	@Override
	public boolean updateEmp(Emp emp) {
		try {
			//1~3 获取数据库连接
			conn = DBUtil.getConnection();
			
			//4.创建PreparedStatement对象
			stat = conn.prepareStatement("update emp set ename = ? where empno = ?");

			//4.1绑定变量值
			stat.setString(1, emp.getEname());
			stat.setInt(2, emp.getEmpno());

			//5.执行查询或更新
			int result = stat.executeUpdate();
			
			//6.结果处理
			if(result > 0)
			{
				return true;
			}
			
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			//7.关闭连接
			DBUtil.close(conn, stat, rs);
		}
		
		return false;
	}

	@Override
	public boolean deleteEmpByEmpno(int empno) {
		try {
			//1~3 获取数据库连接
			conn = DBUtil.getConnection();
			
			//4.创建PreparedStatement对象
			stat = conn.prepareStatement("delete from emp where empno = ?");

			//4.1绑定变量值
			stat.setInt(1, empno);

			//5.执行查询或更新
			int result = stat.executeUpdate();
			
			//6.结果处理
			if(result > 0)
			{
				return true;
			}
			
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			//7.关闭连接
			DBUtil.close(conn, stat, rs);
		}
		
		return false;
	}
}
package com.tencent.dao;

import com.tencent.entity.Emp;
/**
 * <p>Title: IBonusDao</p>  
 * <p>
 *    Description: 
 * 雇员管理-数据访问层DAO(Data Access Object):增、删、改、查
 * </p>  
 * @author xianxian 
 * @date 2023年1月24日
 */
public interface IBonusDao {

	/**
	 * 新增员工
	 * @param emp 新增的员工福利信息
	 * @return true 新增成功   false 新增失败
	 */
	public boolean insertBonus(Emp emp);

}
package com.tencent.dao;

import java.util.List;

import com.tencent.entity.Emp;
/**
 * <p>Title: IEmpDao</p>  
 * <p>
 *    Description: 
 * 雇员管理-数据访问层DAO(Data Access Object):增、删、改、查
 * </p>  
 * @author xianxian 
 * @date 2023年1月24日
 */
public interface IEmpDao {

	/**
	 * 查询所有的员工信息
	 * @return
	 */
	public List<Emp> selectEmps();
	
	/**
	 * 新增员工
	 * @param emp 新增的员工信息
	 * @return true 新增成功   false 新增失败
	 */
	public boolean insertEmp(Emp emp);
	
	/**
	 * 修改员工
	 * @param emp 修改的员工信息
	 * @return true 修改成功   false 修改失败
	 */
	public boolean updateEmp(Emp emp);
	
	/**
	 * 删除员工
	 * @param empno 待删除员工的empno编号
	 * @return true 删除成功   false 删除失败
	 */
	public boolean deleteEmpByEmpno(int empno);

}
  1. entity
package com.tencent.entity;

import java.util.Date;

/**
 * <p>Title: Emp</p>  
 * <p>
 *    Description: 
 * 映射数据库Emp表的实体类
 * </p>  
 * @author xianxian 
 * @date 2023年1月24日
 */
public class Emp {

	/**员工编号*/
	private int empno;
	/**员工姓名*/
	private String ename;
	/**员工职位*/
	private String job;
	/**员工上级经理*/
	private int manager;
	/**员工入职日期*/
	private Date hiredate;
	/**员工薪水*/
	private double salary;
	/**员工奖金*/
	private double comm;
	/**所在部门*/
	private int deptno;

	/**无参构造函数*/
	public Emp()
	{
		super();
	}
	
	/**有参构造函数*/
	public Emp(int empno, String ename, String job, int manager, Date hiredate, double salary, double comm,
			int deptno) {
		super();
		this.empno = empno;
		this.ename = ename;
		this.job = job;
		this.manager = manager;
		this.hiredate = hiredate;
		this.salary = salary;
		this.comm = comm;
		this.deptno = deptno;
	}
	
	/**访问器(get与set方法)*/
	public int getEmpno() {
		return empno;
	}

	public void setEmpno(int empno) {
		this.empno = empno;
	}

	public String getEname() {
		return ename;
	}

	public void setEname(String ename) {
		this.ename = ename;
	}

	public String getJob() {
		return job;
	}

	public void setJob(String job) {
		this.job = job;
	}

	public int getManager() {
		return manager;
	}

	public void setManager(int manager) {
		this.manager = manager;
	}

	public Date getHiredate() {
		return hiredate;
	}

	public void setHiredate(Date hiredate) {
		this.hiredate = hiredate;
	}

	public double getSalary() {
		return salary;
	}

	public void setSalary(double salary) {
		this.salary = salary;
	}

	public double getComm() {
		return comm;
	}

	public void setComm(double comm) {
		this.comm = comm;
	}

	public int getDeptno() {
		return deptno;
	}

	public void setDeptno(int deptno) {
		this.deptno = deptno;
	}

	/**重写Object父类的toString方法*/
	@Override
	public String toString() {
		return "Emp [empno=" + empno + ", ename=" + ename + ", job=" + job + ", manager=" + manager + ", hiredate="
				+ hiredate + ", salary=" + salary + ", comm=" + comm + ", deptno=" + deptno + "]";
	}
}
  1. service
package com.tencent.service;

import java.util.List;

import com.tencent.dao.BonusDaoImpl;
import com.tencent.dao.EmpDaoImpl;
import com.tencent.dao.IBonusDao;
import com.tencent.dao.IEmpDao;
import com.tencent.entity.Emp;
/**
 * 雇员管理--业务逻辑层
 */
public class EmpServiceImpl implements IEmpService{

	@Override
	public List<Emp> selectEmps() {
		/*
		 * 1.业务流程
		 * 		① 查询所有的员工信息(select)
		 */
		IEmpDao empDao = new EmpDaoImpl();
		
		//① 查询所有的员工信息(select)
		List<Emp> empList = empDao.selectEmps();
		
		return empList;
	}

	@Override
	public boolean in(Emp emp) {
		/*
		 * 1.业务流程
		 * 		① 录入一条数据在Emp表中(insert)
		 * 		② 录入一条数据在Bonus表中(insert)
		 */
		//① 录入一条数据在Emp表中(insert)
		IEmpDao empDao = new EmpDaoImpl();
		boolean result = empDao.insertEmp(emp);
		
		//② 录入一条数据在Bonus表中(insert)
		IBonusDao bonusDao = new BonusDaoImpl();
		boolean result2 = bonusDao.insertBonus(emp);

		
		return result && result2;
	}

}
package com.tencent.service;

import java.util.List;

import com.tencent.entity.Emp;

/**
 * 雇员管理--业务逻辑层
 *
 *	1.实现注册功能的业务逻辑:
 *		① 判断用户名是否已存在(select)
 *      ② 实现完成注册(insert)
 *      
 *  2.转账  A->B
 *      ① 判断余额是否足够(select)
 *      ② 判断对方的用户账户是否存在(select)
 *      ③ A账户扣钱(update)
 *      ④ B账户加钱(update)
 */
public interface IEmpService {

	/**
	 * 查询所有员工的信息
	 */
	public List<Emp> selectEmps();
	
	/**
	 * 员工入职
	 */
	public boolean in(Emp emp);
	
}
  1. test
package com.tencent.test;

import java.util.List;

import com.tencent.dao.EmpDaoImpl;
import com.tencent.dao.IEmpDao;
import com.tencent.entity.Emp;

public class Test {

	public static void main(String[] args) {
		IEmpDao dao = new EmpDaoImpl();
		//新增
	/*	Emp param = new Emp();
		param.setEmpno(9999);
		param.setEname("java测试");
		param.setJob("程序猿");
		param.setHiredate(new Date());
		boolean result = dao.insertEmp(param);
		
		System.out.println("新增结果:" + result);*/
		
		//修改
	/*	Emp param = new Emp();
		param.setEmpno(7);
		param.setEname("java测试2");
		
		boolean result = dao.updateEmp(param);
		System.out.println("修改结果:" + result);*/
		
		//删除
		/*int empno = 7;
		boolean result = dao.deleteEmpByEmpno(empno);
		System.out.println("删除结果:" + result);
		*/
		//查询
		List<Emp> empList = dao.selectEmps();
		for (Emp emp : empList) {
			System.out.println(emp);
		}
	}
}
  1. util
package com.tencent.util;

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

/**
 * 日期工具类:
		String -> java.util.Date
		java.util.Date -> String
		
		String -> Calendar
		Calendar -> String
		
		java.sql.Date -> java.util.Date<自动转换>
		java.util.Date -> java.sql.Date<略>
 */
public class DateUtil {
	
	private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	/**
	 * String -> java.util.Date
	 * 
	 * @param source 字符串格式的日期
	 * @return  java.util.Date
	 */
	public static Date stringToUtilDate(String source)
	{
		try {
			return sdf.parse(source);
			
		} catch (ParseException e) {
			e.printStackTrace();
		}
		
		return null;
	}
	
	/**
	 * java.util.Date -> String
	 * 
	 * @param date 日期
	 * @return 格式化之后的日期字符串
	 */
	public static String utilDateToString(Date date)
	{
		return sdf.format(date);
	}
	
	/**
	 * String -> Calendar : 
	 *  		实际转换路径 String -> Date -> Calendar
	 *  
	 * @param source 字符串格式的日期
	 * @return Calendar日历
	 */
	public static Calendar stringToCalendar(String source)
	{
		try {
			//字符串  -> Date
			Date date = sdf.parse(source);
			
			//Date -> Calendar
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(date);
			
			return calendar;
			
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * Calendar -> String : 
	 * 			实际转换路径  Calendar -> Date -> String
	 * 
	 * @param calendar 日历类
	 * @return 格式化后的日期字符串
	 */
	public static String calendarToString(Calendar calendar)
	{
		//Calendar -> Date
		Date date = calendar.getTime();
		
		//Date -> String
		return sdf.format(date);
	}
}
package com.tencent.util;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * 数据库工具类
 */
public class DBUtil {

	private static Properties properties = new Properties();
	
	/**静态代码块:类加载时,仅被执行一次*/
	static{
		try {
			//0.加载外部配置文件db.properties
			properties.load(new FileInputStream("config/db.properties"));
			
			//1.载入JDBC驱动程序
			Class.forName(properties.getProperty("jdbc.driverClassName"));//驱动描述符  oracle.jdbc.driver.OracleDriver
		
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 获取数据库连接
	 * @return
	 */
	public static Connection getConnection()
	{
		try {
			//2.定义连接URL  jdbc:oracle:thin:@<主机IP>:1521:<数据库服务名>
			String url = properties.getProperty("jdbc.url");
			
			//3.建立连接
			Connection conn = DriverManager.getConnection(url, properties.getProperty("jdbc.username"), properties.getProperty("jdbc.password"));
			
			return conn;
			
		} catch (SQLException e) {
			e.printStackTrace();
		} 
		return null;
	}
	
	/**
	 * 关闭数据库资源
	 * @param conn
	 * @param stat
	 * @param rs
	 */
	public static void close(Connection conn,Statement stat,ResultSet rs)
	{
		//7.关闭连接
		//使用顺序:Connection -> Statement -> ResultSet
		//关闭顺序:ResultSet -> Statement -> Connection
		try {
			if(rs != null)
			{
				rs.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		try {
			if(stat != null)
			{
				stat.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		try {
			if(conn != null)
			{
				conn.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
}
  1. view
package com.tencent.view;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Date;

import javax.swing.ButtonGroup;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

import com.tencent.entity.Emp;
import com.tencent.service.EmpServiceImpl;
import com.tencent.service.IEmpService;

public class AddEmpPanel extends JPanel {
	private JTextField txt_empno;
	private JTextField txt_ename;
	private JPasswordField txt_password;
	private final ButtonGroup buttonGroup = new ButtonGroup();
	private JRadioButton rdb_man;
	private JRadioButton rdb_female;
	private JCheckBox cbx_dajidali;
	private JCheckBox cbx_code;
	private JCheckBox cbx_basketball;
	private JCheckBox cbx_sing;
	private JTextArea txt_demo;
	private JComboBox combx_address;

	/**
	 * Create the panel.
	 */
	public AddEmpPanel() {
		setLayout(null);
		
		JLabel label = new JLabel("\u5458\u5DE5\u7F16\u53F7\uFF1A");
		label.setBounds(46, 43, 72, 15);
		add(label);
		
		txt_empno = new JTextField();
		txt_empno.setText("123");
		txt_empno.setBounds(128, 35, 110, 31);
		add(txt_empno);
		txt_empno.setColumns(10);
		
		JLabel label_1 = new JLabel("\u5458\u5DE5\u59D3\u540D\uFF1A");
		label_1.setBounds(321, 43, 72, 15);
		add(label_1);
		
		txt_ename = new JTextField();
		txt_ename.setBounds(403, 36, 126, 28);
		add(txt_ename);
		txt_ename.setColumns(10);
		
		JLabel label_2 = new JLabel("\u5458\u5DE5\u5BC6\u7801\uFF1A");
		label_2.setBounds(46, 88, 72, 15);
		add(label_2);
		
		txt_password = new JPasswordField();
		txt_password.setBounds(128, 80, 110, 31);
		add(txt_password);
		
		JLabel label_3 = new JLabel("\u6027    \u522B\uFF1A");
		label_3.setBounds(321, 88, 72, 15);
		add(label_3);
		
		rdb_man = new JRadioButton("\u7537");
		buttonGroup.add(rdb_man);
		rdb_man.setBounds(403, 84, 46, 23);
		add(rdb_man);
		
		rdb_female = new JRadioButton("\u5973");
		buttonGroup.add(rdb_female);
		rdb_female.setBounds(475, 84, 54, 23);
		add(rdb_female);
		
		JLabel label_4 = new JLabel("\u7231    \u597D\uFF1A");
		label_4.setBounds(46, 142, 72, 15);
		add(label_4);
		
		cbx_dajidali = new JCheckBox("\u5927\u5409\u5927\u5229");
		cbx_dajidali.setBounds(128, 138, 82, 23);
		add(cbx_dajidali);
		
		cbx_code = new JCheckBox("\u5199\u4EE3\u7801");
		cbx_code.setBounds(214, 138, 72, 23);
		add(cbx_code);
		
		cbx_basketball = new JCheckBox("\u7BEE\u7403");
		cbx_basketball.setBounds(288, 138, 54, 23);
		add(cbx_basketball);
		
		cbx_sing = new JCheckBox("\u5531\u6B4C");
		cbx_sing.setBounds(350, 138, 72, 23);
		add(cbx_sing);
		
		JLabel label_5 = new JLabel("\u7C4D    \u8D2F\uFF1A");
		label_5.setBounds(46, 184, 72, 15);
		add(label_5);
		
		combx_address = new JComboBox();
		combx_address.setModel(new DefaultComboBoxModel(new String[] {"", "\u5E7F\u5DDE\u5E02", "\u6C55\u5934\u5E02", "\u6F6E\u5DDE\u5E02", "\u6DF1\u5733\u5E02", "\u6E5B\u6C5F\u5E02", "\u6C5F\u95E8\u5E02"}));
		combx_address.setBounds(128, 181, 89, 21);
		add(combx_address);
		
		JLabel label_6 = new JLabel("\u5907    \u6CE8\uFF1A");
		label_6.setBounds(46, 242, 72, 15);
		add(label_6);
		
		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setBounds(124, 237, 230, 78);
		add(scrollPane);
		
		txt_demo = new JTextArea();
		txt_demo.setLocation(128, 0);
		scrollPane.setViewportView(txt_demo);
		txt_demo.setLineWrap(true);
		
		//新增
		JButton button = new JButton("\u65B0\u589E");
		button.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				//员工编号
				String empno = txt_empno.getText();
				//员工姓名
				String ename = txt_ename.getText();
				//密码
				char[] passwordArray = txt_password.getPassword();
				//性别
				String sex = "不详";
				if(rdb_man.isSelected())
				{
					sex = rdb_man.getText();
				}
				else if(rdb_female.isSelected())
				{
					sex = rdb_female.getText();
				}
				//爱好
				String hobby = "";
				if(cbx_dajidali.isSelected())
				{
					hobby += cbx_dajidali.getText() + ";";
				}
				if(cbx_code.isSelected())
				{
					hobby += cbx_code.getText() + ";";
				}
				if(cbx_basketball.isSelected())
				{
					hobby += cbx_basketball.getText() + ";";
				}
				if(cbx_sing.isSelected())
				{
					hobby += cbx_sing.getText() + ";";
				}
				//籍贯
				String address = (String)combx_address.getSelectedItem();
				//备注
				String demo = txt_demo.getText();
				
				System.out.println("员工编号:" + empno + "\n"
						+ " 员工姓名:" + ename + "\n"
						+ " 密码:" + new String(passwordArray) + "\n"
						+ " 性别:" + sex + "\n"
						+ " 爱好:" + hobby + "\n"
						+ " 籍贯:" + address + "\n"
						+ " 备注:" + demo + "\n");
				
				//将用户输入的数据保存到Emp对象
				Emp emp = new Emp();
				emp.setEname(ename);
				emp.setHiredate(new Date());
				
				//调用service方法完成员工入职
				IEmpService empService = new EmpServiceImpl();
				boolean result = empService.in(emp);
				
				//获取新增结果
				System.out.println("员工入职是否成功:" + result);
				if(result)
				{
					JOptionPane.showMessageDialog(null, "员工【" + ename + "】新增成功", "温馨提示", JOptionPane.INFORMATION_MESSAGE);
				}
				else 
				{
					JOptionPane.showMessageDialog(null, "员工【" + ename + "】新增失败,请联系管理员:110", "温馨提示", JOptionPane.INFORMATION_MESSAGE);
				}
			}
		});
		button.setBounds(535, 319, 93, 23);
		add(button);
		
		JButton button_1 = new JButton("\u91CD\u7F6E");
		button_1.setBounds(417, 319, 93, 23);
		add(button_1);

	}
}
package com.tencent.view;

import java.awt.EventQueue;
import java.awt.Toolkit;

import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JSeparator;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.EmptyBorder;
import javax.swing.JToolBar;
import javax.swing.JButton;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class MainFrame extends JFrame {

	private JPanel contentPane;
	private JPanel panel;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					MainFrame frame = new MainFrame();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}
	
	static{
		try {
//			UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");//Nimbus风格,jdk6 update10版本以后的才会出现
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());//当前系统风格
//			UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");//Motif风格,是蓝黑
//			UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());//跨平台的Java风格
//			UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");//windows风格
//			UIManager.setLookAndFeel("javax.swing.plaf.windows.WindowsLookAndFeel");//windows风格
//			UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");//java风格
//			UIManager.setLookAndFeel("com.apple.mrj.swing.MacLookAndFeel");//待考察,
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (UnsupportedLookAndFeelException e) {
			e.printStackTrace();
		}
	}

	/**
	 * Create the frame.
	 */
	public MainFrame() {
		setIconImage(Toolkit.getDefaultToolkit().getImage("icon\\layers.png"));
		setTitle("\u96C7\u5458\u7BA1\u7406\u7CFB\u7EDF");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 761, 449);
		
		JMenuBar menuBar = new JMenuBar();
		setJMenuBar(menuBar);
		
		JMenu menu = new JMenu("\u5458\u5DE5\u7BA1\u7406");
		menuBar.add(menu);
		
		JMenu menu_4 = new JMenu("\u65B0\u589E\u5458\u5DE5");
		menu.add(menu_4);
		
		JMenuItem menuItem = new JMenuItem("\u65B0\u589E\u666E\u901A\u5458\u5DE5");
		menu_4.add(menuItem);
		
		JMenuItem menuItem_1 = new JMenuItem("\u65B0\u589E\u7BA1\u7406\u5458");
		menu_4.add(menuItem_1);
		
		//查询
		JMenuItem menuItem_2 = new JMenuItem("\u67E5\u8BE2\u5458\u5DE5");
		menuItem_2.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				//1.先移除原panel中所有的内容
				panel.removeAll();
				panel.repaint();
				
				//2.再想panel中添加新的内容(查询员工的界面)
				SelectEmpPanel selectEmpPanel = new SelectEmpPanel();
				selectEmpPanel.setBounds(0, 0, 745, 352);
				panel.add(selectEmpPanel);
			}
		});
		menu.add(menuItem_2);
		
		JSeparator separator = new JSeparator();
		menu.add(separator);
		
		JMenuItem menuItem_3 = new JMenuItem("\u9000\u51FA");
		menu.add(menuItem_3);
		
		JMenu menu_1 = new JMenu("\u90E8\u95E8\u7BA1\u7406");
		menuBar.add(menu_1);
		
		JMenu menu_2 = new JMenu("\u5C97\u4F4D\u7BA1\u7406");
		menuBar.add(menu_2);
		
		JMenu menu_3 = new JMenu("\u7CFB\u7EDF\u8BBE\u7F6E");
		menuBar.add(menu_3);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);
		
		JToolBar toolBar = new JToolBar();
		toolBar.setBounds(0, 0, 745, 35);
		contentPane.add(toolBar);
		
		//新增员工
		JButton button = new JButton("");
		button.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				//1.先移除原panel中所有的内容
				panel.removeAll();
				panel.repaint();
				
				//2.再想panel中添加新的内容(新增员工的界面)
				AddEmpPanel addEmpPanel = new AddEmpPanel();
				addEmpPanel.setBounds(0, 0, 745, 352);
				panel.add(addEmpPanel);
			}
		});
		button.setToolTipText("\u65B0\u589E\u5458\u5DE5");
		button.setIcon(new ImageIcon("icon\\add.png"));
		toolBar.add(button);
		
		JButton button_1 = new JButton("");
		button_1.setToolTipText("\u8C03\u8F6C\u90E8\u95E8");
		button_1.setIcon(new ImageIcon("icon\\layout_edit.png"));
		toolBar.add(button_1);
		
		JButton button_2 = new JButton("");
		button_2.setToolTipText("\u8C03\u6574\u85AA\u8D44");
		button_2.setIcon(new ImageIcon("icon\\money.png"));
		toolBar.add(button_2);
		
		panel = new JPanel();
		panel.setBounds(0, 38, 745, 352);
		contentPane.add(panel);
		panel.setLayout(null);
		
		JLabel lblNewLabel = new JLabel("");
		lblNewLabel.setIcon(new ImageIcon("icon\\bg.jpg"));
		lblNewLabel.setBounds(0, 0, 745, 352);
		panel.add(lblNewLabel);
		
		//窗体居中
		this.setLocationRelativeTo(null);
	}
}
package com.tencent.view;

import java.util.List;

import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

import com.tencent.entity.Emp;
import com.tencent.service.EmpServiceImpl;
import com.tencent.service.IEmpService;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JComboBox;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;

public class SelectEmpPanel extends JPanel {
	private JTable table;
	private JTextField textField;
	private JTextField textField_1;

	/**
	 * Create the panel.
	 */
	public SelectEmpPanel() {
		setLayout(null);
		
		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setBounds(10, 38, 725, 304);
		add(scrollPane);
		
		/*
		 * 调用service层方法,获取查询的数据
		 */
		IEmpService empService = new EmpServiceImpl();
		List<Emp> empList = empService.selectEmps();
		
		//List ——> Object[][]
		Object[][] values = new Object[empList.size()][8];
		
		Object[] objArray = empList.toArray();
		int k = 0;
		for (Object object : objArray) {
			Emp emp = (Emp)object;
			
			values[k++] = new Object[]{emp.getEmpno(),emp.getEname(),emp.getJob(),emp.getManager(),emp.getHiredate(),emp.getSalary(),emp.getComm(),emp.getDeptno()};
		}
		
		table = new JTable();
		scrollPane.setViewportView(table);
		table.setModel(new DefaultTableModel(
			values,
			new String[] {
				"\u96C7\u5458\u7F16\u53F7", "\u96C7\u5458\u59D3\u540D", "\u804C\u4F4D", "\u4E0A\u7EA7\u7ECF\u7406", "\u5165\u804C\u65E5\u671F", "\u85AA\u8D44", "\u5956\u91D1", "\u90E8\u95E8\u7F16\u53F7"
			}
		));
		
		JLabel label = new JLabel("\u96C7\u5458\u7F16\u53F7\uFF1A");
		label.setBounds(30, 13, 67, 15);
		add(label);
		
		textField = new JTextField();
		textField.setBounds(99, 10, 66, 21);
		add(textField);
		textField.setColumns(10);
		
		JLabel label_1 = new JLabel("\u96C7\u5458\u59D3\u540D\uFF1A");
		label_1.setBounds(190, 13, 67, 15);
		add(label_1);
		
		textField_1 = new JTextField();
		textField_1.setBounds(267, 10, 66, 21);
		add(textField_1);
		textField_1.setColumns(10);
		
		JLabel label_2 = new JLabel("\u90E8\u95E8\uFF1A");
		label_2.setBounds(358, 13, 54, 15);
		add(label_2);
		
		JComboBox comboBox = new JComboBox();
		comboBox.setModel(new DefaultComboBoxModel(new String[] {"", "10", "20", "30", "40"}));
		comboBox.setBounds(417, 10, 77, 21);
		add(comboBox);
		
		JButton button = new JButton("\u67E5\u8BE2");
		button.setBounds(549, 9, 93, 23);
		add(button);
	}
}

效果图


分割线


相关信息

以上就是我关于 76-Java-JDBC与java数据库编程-基于MVC三层编程_小项目示例代码.md 知识点的整理与总结的全部内容,希望对你有帮助。。。。。。。

上次编辑于:
贡献者: 涎涎
评论
  • 按正序
  • 按倒序
  • 按热度
Powered by Waline v2.15.4