java swing 實現數據庫的增刪查改

         最近一個實習生問我,swing好難啊,就是jtable的增刪查改都作不出來了,我也很久沒有作了,各類文檔,各類查找,各類百度終因而完成了一個小的項目,也就是所說的增刪除查改。java

       不廢話了,上代碼。mysql

1 工具

     1)IDE 工具:eclipse   windowbuildersql

     2)數據庫:MYSQL5.6數據庫

2  代碼 

     1)數據庫設計:

      

/*
Navicat MySQL Data Transfer

Source Server         : localhost
Source Server Version : 50614
Source Host           : localhost:3306
Source Database       : test

Target Server Type    : MYSQL
Target Server Version : 50614
File Encoding         : 65001

Date: 2014-12-09 15:53:57
*/

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for dept
-- ----------------------------
DROP TABLE IF EXISTS `dept`;
CREATE TABLE `dept` (
  `deptid` int(11) NOT NULL AUTO_INCREMENT,
  `deptname` varchar(20) DEFAULT NULL,
  PRIMARY KEY (`deptid`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `userid` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(20) DEFAULT NULL,
  `deptid` int(11) DEFAULT NULL,
  `birth` varchar(20) DEFAULT NULL,
  PRIMARY KEY (`userid`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;

2)代碼

       1)數據庫鏈接類

     

package util;

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

/**
 * @author zhanglj
 *數據庫鏈接工具輔助類
 */

public class DBCon {
	public static final String DRIVER="com.mysql.jdbc.Driver";
	public static final String URL="jdbc:mysql://localhost:3306/test";
	public static final String USER="root";
	public static final String PWD="root";
	private Connection con;
	private PreparedStatement ps;
	private ResultSet rs;
	
	
	public DBCon(){
		try {
			//加載驅動程序
			Class.forName(DRIVER);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
	/**
	 * @return返回數據庫鏈接
	 */
	public Connection getCon(){
		try {
			con=DriverManager.getConnection(URL, USER, PWD);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return con;
	}
	
	/**
	 * 關閉資源 
	 */
	public void closeAll(){
		if(rs!=null){
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if(ps!=null)
			try {
				ps.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		if(con!=null)
			try {
				con.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
	}
	
	/**
	 * @param sql��sql語句 
	 * @param pras��������參數列表 
	 * @return受影響的條數
	 */
	public int update(String sql,Object... pras){
		int resu=0;
		con=getCon();
		try {
			ps=con.prepareStatement(sql);
			if(pras!=null){
				for(int i=0;i<pras.length;i++){
					ps.setObject(i+1, pras[i]);
				}
			}
			resu=ps.executeUpdate();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			closeAll();
		}
		return resu;
	}
	
	
	/**
	 * @param sql sql語句 
	 * @param pras
	 * @return 結果集
	 */
	public ResultSet query(String sql,Object... pras){
		con=getCon();
		try {
			ps=con.prepareStatement(sql);
			if(pras!=null){
				for(int i=0;i<pras.length;i++){
					ps.setObject(i+1, pras[i]);
				}
			}
			rs=ps.executeQuery();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return rs;
	}
}

2)實體模型

package entity;

import java.io.Serializable;

/**
 * @author zhanglj
 * 用戶實體
 *
 */
public class User implements Serializable {
	private int userid;
	private String name;
	private int deptid;
	private String birth;
	public int getUserid() {
		return userid;
	}
	public void setUserid(int userid) {
		this.userid = userid;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getDeptid() {
		return deptid;
	}
	public void setDeptid(int deptid) {
		this.deptid = deptid;
	}
	public String getBirth() {
		return birth;
	}
	public void setBirth(String birth) {
		this.birth = birth;
	}
	
	
}

部門表實體模型app

package entity;

import java.io.Serializable;

public class Dept implements Serializable {
	private int deptid;
	private String deptname;

	public int getDeptid() {
		return deptid;
	}

	public void setDeptid(int deptid) {
		this.deptid = deptid;
	}

	public String getDeptname() {
		return deptname;
	}

	public void setDeptname(String deptname) {
		this.deptname = deptname;
	}

	public Dept(int deptid, String deptname) {
		super();
		this.deptid = deptid;
		this.deptname = deptname;
	}

	public Dept() {
		super();
		// TODO Auto-generated constructor stub
	}

	@Override
	public String toString() {
		return this.deptname;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + deptid;
		result = prime * result
				+ ((deptname == null) ? 0 : deptname.hashCode());
		return result;
	}
	public Dept(int deptid){
		this.deptid=deptid;
	}
	@Override
	public boolean equals(Object obj) {
		Dept dept=(Dept) obj;
		return dept.getDeptid()==this.getDeptid();
	}
	
	

}


3)數據訪問接口

用戶表數據訪問接口:
eclipse

package dao;

import java.util.List;

import entity.User;

/**
 * @author zhanglj
 *數據訪問接口
 */
public interface IUserDao {
	/**
	 * 添加
	 * @param user
	 * @return
	 */
	boolean add(User user);
	/**
	 * 修改
	 * @param user
	 * @return
	 */

	boolean update(User user);
	/**
	 * 刪除
	 * @param userid
	 * @return
	 */
	boolean delete(int userid);
	
	/**
	 * 經過Id查找 一條記錄
	 * @param userid
	 * @return
	 */
	User QueryById(int userid);
	
	/**
	 * 查找所有記錄
	 * @return
	 */
	List<User> queryAll();
}
部門表數據訪問接口:

package dao;


import java.util.List;

import entity.Dept;

/**
 * @author zhanglj
 * 部門表數據訪問接口
 *
 */
public interface IDeptDao {
	/**
	 * 查找所有部門
	 * @return
	 */
	List<Dept> queryAll();
}

4)數據訪問接口的實現

用戶表數據訪問的實現 :數據庫設計

package dao.impl;

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

import dao.IUserDao;
import util.DBCon;
import entity.User;

public class UserDaoImpl implements IUserDao {
	DBCon util = new DBCon();

	@Override
	public boolean add(User user) {

		return util.update("insert into user(name,deptid,birth) values(?,?,?)",
				user.getName(), user.getDeptid(), user.getBirth()) > 0;
	}

	@Override
	public boolean update(User user) {
		return util.update(
				"update user set name=?,deptid=?,birth=? where userid=?",
				user.getName(), user.getDeptid(), user.getBirth(),
				user.getUserid()) > 0;
	}

	@Override
	public boolean delete(int userid) {
		
		return util.update("delete from user where userid=?", userid)>0;
	}

	@Override
	public User QueryById(int userid) {
		return _user(util.query("select * from user where userid=?", userid));
	}

	@Override
	public List<User> queryAll() {
		return  _list(util.query("select * from user"));
	}
	
	private User _user(ResultSet rs){
		User user=null;
		try {
			if(rs.next()){
				user=new User();
				user.setBirth(rs.getString("birth"));
				user.setDeptid(rs.getInt("deptid"));
				user.setName(rs.getString("name"));
				user.setUserid(rs.getInt("userid"));
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			util.closeAll();
		}
		return user;
	}
	
	private List<User> _list(ResultSet rs){
		List<User> _list=new ArrayList<User>();
		try {
			while(rs.next()){
				User user=new User();
				user.setBirth(rs.getString("birth"));
				user.setDeptid(rs.getInt("deptid"));
				user.setName(rs.getString("name"));
				user.setUserid(rs.getInt("userid"));
				_list.add(user);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			util.closeAll();
		}
		return _list;
	}

}


部門表數據訪問的實現 :
ide

package dao.impl;

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

import util.DBCon;
import dao.IDeptDao;
import entity.Dept;

public class DeptDaoImpl implements IDeptDao{
	DBCon util=new DBCon();
	@Override
	public List<Dept> queryAll() {
		// TODO Auto-generated method stub
		return _list(util.query("select * from dept"));
	}
	private List<Dept> _list(ResultSet rs){
		List<Dept> _list=new ArrayList<Dept>();
		try {
			while(rs.next()){
				Dept dept=new Dept();
				dept.setDeptid(rs.getInt("deptid"));
				dept.setDeptname(rs.getString("deptname"));
				_list.add(dept);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			util.closeAll();
		}
		return _list;
	}

}

5)swing的實現

主窗口:工具

package ui;

import java.awt.BorderLayout;

public class MainFrame extends JFrame implements ActionListener {

	 JPanel contentPane;
	 JPanel panelBottom;
	private JButton btnDel;
	private JButton btnAdd;
	private AddPanel add;
	private QueryPanel query;
	/**
	 * 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();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public MainFrame() {
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 546, 383);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		contentPane.setLayout(new BorderLayout(0, 0));
		setContentPane(contentPane);
		
		JPanel panel = new JPanel();
		contentPane.add(panel, BorderLayout.NORTH);
		panel.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
		
		JButton btnLoadData = new JButton("獲取數據");
		btnLoadData.setActionCommand("loaddata");
		panel.add(btnLoadData);
		
		btnDel = new JButton("刪除所選");
		panel.add(btnDel);
		btnDel.setActionCommand("del");
		
		btnAdd = new JButton("添加用戶");
		panel.add(btnAdd);
		btnAdd.setActionCommand("add");
		
		panelBottom = new JPanel();
		panelBottom.setBackground(Color.LIGHT_GRAY);
		contentPane.add(panelBottom, BorderLayout.CENTER);
		panelBottom.setLayout(new BorderLayout(0,0));
		
		btnDel.addActionListener(this);
		btnLoadData.addActionListener(this);
		btnAdd.addActionListener(this);
		
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		String command=e.getActionCommand();
		System.out.println(command);
		if(command.equals("add")){
			panelBottom.removeAll();
			add=new AddPanel();
			panelBottom.add(add,BorderLayout.CENTER);
			panelBottom.updateUI();
		}else if(command.equals("loaddata")){
			panelBottom.removeAll();
			query=new QueryPanel();
			panelBottom.add(query,BorderLayout.CENTER);
			panelBottom.updateUI();
		}else if(command.equals("del")){
			if(query==null){
				JOptionPane.showMessageDialog(null, "沒有數據");
				return;
			}
			query.del();
		}
		
	}

}

添加面板

package ui;

import java.awt.BorderLayout;

public class AddPanel extends JPanel {
	private JTextField txtName;
	private JTextField txtBirth;
	private JComboBox cmbDept;
	private IUserDao userDao;
	private IDeptDao deptDao;
	private QueryPanel query;
	private MainFrame main;
	/**
	 * Create the panel.
	 */
	public AddPanel() {
		setLayout(null);
		
		JLabel label = new JLabel("用戶名:");
		label.setBounds(86, 68, 54, 15);
		add(label);
		
		txtName = new JTextField();
		txtName.setBounds(150, 65, 146, 18);
		add(txtName);
		txtName.setColumns(10);
		
		JLabel label_1 = new JLabel("部門:");
		label_1.setBounds(86, 114, 54, 15);
		add(label_1);
		
		userDao=new UserDaoImpl();
		deptDao=new DeptDaoImpl();
		List<Dept> list=deptDao.queryAll();
		
		
		cmbDept = new JComboBox(list.toArray());
		cmbDept.setBounds(150, 110, 146, 23);
		add(cmbDept);
		
		JLabel label_2 = new JLabel("生日:");
		label_2.setBounds(86, 163, 54, 15);
		add(label_2);
		
		txtBirth = new JTextField();
		txtBirth.setBounds(150, 160, 146, 23);
		add(txtBirth);
		txtBirth.setColumns(10);
		
		JButton btnNewButton = new JButton("添加用戶");
		btnNewButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				String name=txtName.getText();
				String birth=txtBirth.getText();
				Dept dept=(Dept) cmbDept.getSelectedItem();
				User user=new User();
				user.setBirth(birth);
				user.setName(name);
				user.setDeptid(dept.getDeptid());
				if(userDao.add(user)){
					JOptionPane.showMessageDialog(null, "插入成功");
					txtName.setText("");
					txtBirth.setText("");
				
				}else{
					JOptionPane.showMessageDialog(null, "插入失敗");
				}
				
			}
		});
		btnNewButton.setBounds(150, 217, 116, 23);
		add(btnNewButton);

	}
}

查詢,修改,刪除面板

package ui;

import java.awt.BorderLayout;

public class QueryPanel extends JPanel {
	private JTable table;
	private DefaultTableModel model;// 用於存儲表格數據
	private IDeptDao deptDao;
	private IUserDao userDao;
	private String oldValue = "";// 保存單元格編輯 前的值

	/**
	 * Create the panel.
	 */
	public QueryPanel() {
		setLayout(new BorderLayout(0, 0));

		JScrollPane scrollPane = new JScrollPane();
		add(scrollPane, BorderLayout.CENTER);

		table = new JTable();

		scrollPane.setColumnHeaderView(table);
		// 初始化存儲表格數據的對象
		model = new DefaultTableModel(new Object[][] {}, new String[] { "用戶編號",
				"用戶名", "所屬部門", "出生日期" });
		// 將數據綁定到對象中
		table.setModel(model);
		table.setRowHeight(30);

		scrollPane.setViewportView(table);

		deptDao = new DeptDaoImpl();
		userDao = new UserDaoImpl();
		loadData();
		// 爲表格綁定修改值後的事件
		model.addTableModelListener(new TableModelListener() {

			@Override
			public void tableChanged(TableModelEvent e) {
				if (e.getColumn() < 0)
					return;
				String nVal = table.getValueAt(e.getLastRow(), e.getColumn())
						.toString();
				// 若是舊的值 和新的值同樣,直接 返回
				if (nVal.equals(oldValue)) {
					return;
				}
				// 判斷當前編輯的單元格是不是主鍵列
				if (e.getColumn() == 0) {
					// 還原舊的值
					table.setValueAt(oldValue, e.getLastRow(), e.getColumn());
					return;
				}
				// 更新數據
				User user = new User();
				user.setUserid(Integer.valueOf(table.getValueAt(e.getLastRow(),
						0).toString()));
				user.setName(table.getValueAt(e.getLastRow(), 1).toString());
				user.setBirth(table.getValueAt(e.getLastRow(), 3).toString());
				Dept dept = (Dept) table.getValueAt(e.getLastRow(), 2);
				user.setDeptid(dept.getDeptid());

				userDao.update(user);

				loadData();
			}
		});
	}

	public void loadData() {
		// 清除舊的數據
		model.getDataVector().clear();
		// 查詢部門數據
		List<Dept> deptList = deptDao.queryAll();

		JComboBox cob = new JComboBox(deptList.toArray());
		// 建立一個使用下拉框代替編輯框的單元格對象
		DefaultCellEditor dept = new DefaultCellEditor(cob);
		// 獲取表格的列model對象
		TableColumnModel col = table.getColumnModel();
		// 獲取部門的列,設置這個列爲下拉框列類型
		col.getColumn(2).setCellEditor(dept);
		// 查詢全部的用戶信息
		List<User> list = userDao.queryAll();
		// 遍歷每一條數據,添加到model中
		int i = 0;
		for (User user : list) {
			// 添加 行數據
			cob.setSelectedItem(new Dept(user.getDeptid()));
			model.addRow(new Object[] { user.getUserid(), user.getName(),
					cob.getSelectedItem(), user.getBirth() });
		}
	}

	public void del() {
		if (table.getSelectedRowCount() <= 0) {
			JOptionPane.showMessageDialog(null, "請選擇要刪除的數據行");
			return;
		}
		int result = JOptionPane.showConfirmDialog(null, "是否肯定要刪除");
		// 判斷用戶是否點擊
		if (result == JOptionPane.OK_OPTION) {
			int userid = Integer.valueOf(table.getValueAt(
					table.getSelectedRow(), 0).toString());
			userDao.delete(userid);
			loadData();
		}
	}

}

效果:



這樣就完成了,附上源代碼 

ui

相關文章
相關標籤/搜索