先写一个类似于工具类,用于在数据库中增删改查。
package com.homework;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
public class DButil {
private static final String URL;
private static final String USER;
private static final String PASSWORD;
private Connection con = null;
private PreparedStatement pre = null;
private ResultSet rs = null;
private ResultSetMetaData res = null;
private Field f = null;
static {
Properties p = new Properties();
try {
p.load(new FileInputStream(new File("src\\login.properties")));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
URL = p.getProperty("url");
USER = p.getProperty("user");
PASSWORD = p.getProperty("password");
}
private Connection init() throws SQLException, ClassNotFoundException {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(URL, USER, PASSWORD);
return con;
}
public boolean upDate(String sql, Object... decs) throws SQLException, ClassNotFoundException {
con = init();
pre = con.prepareStatement(sql);
for (int i = 0; i < decs.length; i++) {
pre.setObject(i + 1, decs[i]);
}
int result = pre.executeUpdate();
pre.close();
con.close();
return result > 0;
}
public <T> List<T> result(Class<T> clz, String sql, Object... decs) throws ClassNotFoundException, SQLException,
NoSuchFieldException, SecurityException, InstantiationException, IllegalAccessException,
NoSuchMethodException, IllegalArgumentException, InvocationTargetException {
List<T> list = new ArrayList<>();
con = init();
pre = con.prepareStatement(sql);
for (int i = 0; i < decs.length; i++) {
pre.setObject(i + 1, decs[i]);
}
// 执行sql语句获得一个二维数组
rs = pre.executeQuery();
// 获取关于表的信息
res = pre.getMetaData();
// 新建表
int result = res.getColumnCount();
while (rs.next()) {
Constructor<T> cst = clz.getConstructor();
T o = cst.newInstance();
for (int i = 0; i < result; i++) {
f = clz.getDeclaredField(res.getColumnName(i + 1));
if (!rs.wasNull()) {
f.setAccessible(true);
f.set(o, rs.getObject(i + 1));
}
}
list.add(o);
}
rs.close();
pre.close();
con.close();
return list;
}
}
在写一个Bean 用于传输语句 我的数据库有的格式是 sson是主键 int 行 sname是名字 varchar(50)型
package com.homework.beans;
public class I_student {
private int sson;
private String sname;
public int getSson() {
return sson;
}
public void setSson(int sson) {
this.sson = sson;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
@Override
public String toString() {
return "I_student [sson=" + sson + ", sname=" + sname + "]";
}
}
下面是Dao层的实现类 Dao层的接口我就不写了 要有接口 用于解耦
package com.homework.dao.impl;
import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.homework.DButil;
import com.homework.beans.I_student;
import com.homework.dao.StudentDao;
public class StudentDaoImpl implements StudentDao{
private DButil db = new DButil();
@Override
public boolean addition(I_student stu) throws ClassNotFoundException, SQLException {
String sql = "insert into i_student value(?,?)";
return db.upDate(sql,stu.getSson(),stu.getSname());
}
@Override
public boolean delete(int son) throws ClassNotFoundException, SQLException {
String sql = "delete from i_student where sson = ?";
return db.upDate(sql, son);
}
@Override
public boolean Update(I_student stu) throws ClassNotFoundException, SQLException {
String sql = "Update i_student set sname = ? where sson = ?";
db.upDate(sql, stu.getSname(),stu.getSson());
return false;
}
@Override
public List<I_student> select(I_student stu) throws ClassNotFoundException, SQLException, NoSuchFieldException, SecurityException, InstantiationException, IllegalAccessException, NoSuchMethodException, IllegalArgumentException, InvocationTargetException {
List <I_student> list = new ArrayList<>();
if(stu.getSname().trim().equals("") && stu.getSson() == 0){
String sql = "select * from i_student";
list = db.result(I_student.class, sql);
}
if(!stu.getSname().trim().equals("") && stu.getSson() == 0){
String sql = "select * from i_student where sname = ?";
list = db.result(I_student.class, sql, "%"+stu.getSname()+"%");
}
if(stu.getSname().trim().equals("") && stu.getSson() != 0){
String sql = "select * from i_student where sson = ?";
list = db.result(I_student.class, sql, stu.getSson());
}
if(!stu.getSname().trim().equals("") && stu.getSson() != 0){
String sql = "select * from i_student where sson = ? and sname = ?";
list = db.result(I_student.class, sql, stu.getSson(),"%"+stu.getSname()+"%");
}
return list;
}
}
下面我是用swing简单实现了一些增删改查 BUG比较多 但是还是完成了
显示增加数据界面
package com.homework.ui;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import com.homework.beans.I_student;
import com.homework.dao.StudentDao;
import com.homework.dao.impl.StudentDaoImpl;
public class StudentUIAdd extends JFrame{
private JLabel Jlsno;
private JLabel Jlname;
private JTextField JFsno;
private JTextField JFname;
private JButton Jok;
private StudentDao sd;
public StudentUIAdd(){
/*
*布置空布局 并且设置大小
*/
super("增加");
setLayout(null);
// this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(300,500);
/*
* 添加JLable
*/
Jlsno = new JLabel("学号:");
Jlsno.setBounds(30, 50, 50, 50);
add(Jlsno);
Jlname = new JLabel("姓名:");
Jlname.setBounds(30, 150, 50, 50);
add(Jlname);
/*
*添加 JTextField
*/
JFsno = new JTextField();
JFsno.setBounds(100, 50, 100, 50);
add(JFsno);
JFname = new JTextField();
JFname.setBounds(100, 150, 100, 50);
add(JFname);
/*
* 添加Jok 按钮 并设计单击事件
*/
Jok = new JButton("保存");
Jok.setBounds(100, 250, 100, 50);
Jok.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String sno = JFsno.getText();
String sname = JFname.getText();
int sno1 = 0;
try{
sno1 = new Integer(sno);
}catch(Exception e1){
return;
}
I_student stu = new I_student();
stu.setSname(sname);
stu.setSson(sno1);
sd = new StudentDaoImpl();
try {
System.out.println(sd.addition(stu));
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
add(Jok);
}
// public static void main(String[] args) {
// new StudentUIAdd().setVisible(true);
//
// }
}
下面是改变数据界面 我设置的是主键不可改 可改姓名
package com.homework.ui;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import com.homework.beans.I_student;
import com.homework.dao.StudentDao;
import com.homework.dao.impl.StudentDaoImpl;
public class StudentUIUpa extends JFrame{
private JLabel Jlsno;
private JLabel Jlname;
private JTextField JFsno;
private JTextField JFname;
private JButton Jok;
private StudentDao sd;
public StudentUIUpa(I_student stu){
/*
*布置空布局 并且设置大小
*/
super("修改");
setLayout(null);
// this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(300,500);
/*
* 添加JLable
*/
Jlsno = new JLabel("学号:");
Jlsno.setBounds(30, 50, 50, 50);
add(Jlsno);
Jlname = new JLabel("姓名:");
Jlname.setBounds(30, 150, 50, 50);
add(Jlname);
/*
*添加 JTextField
*/
JFsno = new JTextField();
JFsno.setBounds(100, 50, 100, 50);
add(JFsno);
int str = stu.getSson();
JFsno.setText(String.valueOf(str));
//设置不可修改
JFsno.setEditable(false);
JFname = new JTextField();
JFname.setBounds(100, 150, 100, 50);
JFname.setText(stu.getSname());
add(JFname);
/*
* 添加Jok 按钮 并设计单击事件
*/
Jok = new JButton("修改");
Jok.setBounds(100, 250, 100, 50);
Jok.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String sno = JFsno.getText();
String sname = JFname.getText();
int sno1 = 0;
try{
sno1 = new Integer(sno);
}catch(Exception e1){
return;
}
I_student stu = new I_student();
stu.setSname(sname);
stu.setSson(sno1);
sd = new StudentDaoImpl();
try {
System.out.println(sd.Update(stu));
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
add(Jok);
}
// public static void main(String[] args) {
// new StudentUIUpa().setVisible(true);
//
// }
}
最后是查找 以及添加增加功能和修改功能
package com.homework.ui;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;
import com.homework.beans.I_student;
import com.homework.dao.StudentDao;
import com.homework.dao.impl.StudentDaoImpl;
public class StudentUISele extends JFrame{
private JLabel son;
private JLabel name;
private JTextField Json;
private JTextField Jname;
private JButton Jok;
private JButton Jadd;
private JButton Jdele;
private JButton Jup;
private JTable table;
private I_student stu;
private StudentDao sd;
private ArrayList<Vector> list = null;
private DefaultTableModel model = null;
private Vector<String> columnNames = null;
private List<I_student> li = null;
public StudentUISele() throws ClassNotFoundException, NoSuchFieldException, SecurityException, InstantiationException, IllegalAccessException, NoSuchMethodException, IllegalArgumentException, InvocationTargetException, SQLException{
setLayout(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(500,500);
son = new JLabel("学号");
son.setBounds(20, 50, 50, 40);
add(son);
name = new JLabel("姓名");
name.setBounds(200,50,50,40);
add(name);
/*
* 文本框布局
*/
Json = new JTextField();
Json.setBounds(90, 50, 80, 40);
add(Json);
Jname = new JTextField();
Jname.setBounds(270, 50, 80, 40);
add(Jname);
/*
* 按钮布局
*/
Jok = new JButton("查找");
Jok.setBounds(370, 50, 80, 40);
Jok.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
result();
} catch (ClassNotFoundException | NoSuchFieldException | SecurityException | InstantiationException
| IllegalAccessException | NoSuchMethodException | IllegalArgumentException
| InvocationTargetException | SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
add(Jok);
Jadd = new JButton("新建");
Jadd.setBounds(50,100,70,40);
Jadd.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
StudentUIAdd st = new StudentUIAdd();
st.setVisible(true);
}
});
add(Jadd);
Jdele = new JButton("删除");
Jdele.setBounds(170,100,70,40);
Jdele.setEnabled(false);
Jdele.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
try {
sd.delete(stu.getSson());
} catch (ClassNotFoundException | SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
result();
} catch (ClassNotFoundException | NoSuchFieldException | SecurityException | InstantiationException
| IllegalAccessException | NoSuchMethodException | IllegalArgumentException
| InvocationTargetException | SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
add(Jdele);
Jup = new JButton("修改");
Jup.setBounds(290,100,70,40);
Jup.setEnabled(false);
Jup.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
new StudentUIUpa(stu).setVisible(true);
}
});
add(Jup);
/*
* 表布局
*/
inittable();
add(table);
}
private void inittable() throws ClassNotFoundException, NoSuchFieldException, SecurityException, InstantiationException, IllegalAccessException, NoSuchMethodException, IllegalArgumentException, InvocationTargetException, SQLException {
columnNames = new Vector<>();
columnNames.add("学号");
columnNames.add("姓名");
model = new DefaultTableModel(columnNames, 0);
table = new JTable(model);
result();// 从数据库中读取二维表绑定到table中
table.setBounds(50,170,350,250);
table.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
Jdele.setEnabled(true);
Jup.setEnabled(true);
stu = new I_student();
int temp1 =new Integer(model.getValueAt(table.getSelectedRow(), 0).toString());
stu.setSson(temp1);
stu.setSname(model.getValueAt(table.getSelectedRow(), 1).toString());
// System.out.println(stu.getSname()+"\t"+stu.getSson());
}
});
}
/**
* 是表显示当前全部数据,相当于刷新
*
*/
private void result() throws ClassNotFoundException, NoSuchFieldException, SecurityException, InstantiationException, IllegalAccessException, NoSuchMethodException, IllegalArgumentException, InvocationTargetException, SQLException {
/*
* 清空表
*/
int rowCount= model.getRowCount();
for (int i = 0; i < rowCount; i++) {
model.removeRow(0);
}
I_student student = new I_student();
// stu.setSname("");
// stu.setSson(0);
String str = Json.getText();
String str1 = Jname.getText();
student.setSname(str1);
if(str.trim().equals("")){
student.setSson(0);
}else{
int Temp = new Integer(str);
student.setSson(Temp);
}
sd = new StudentDaoImpl();
li = sd.select(student);
for (I_student i_student : li) {
Vector v = new Vector<>();
v.add(i_student.getSson());
v.add(i_student.getSname());
model.addRow(v);
}
}
public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, SecurityException, InstantiationException, IllegalAccessException, NoSuchMethodException, IllegalArgumentException, InvocationTargetException, SQLException {
new StudentUISele().setVisible(true);
}
}