Java_数据库操作图形化
2020年12月7日下午8:08
这个就有点神经了,数据库本来就是直接写操作语句,整个要求图形化操作就离谱
要求
编写通过Java访问数据库的程序。
例如:成绩管理、图书管理、货物管理、宿舍管理、课程管理等等,请自由选择一个信息管理类的系统,不能选择教材上的例子。通过Java程序访问数据库,实现显示、查找、插入、删除、修改等操作。要求用可视化图形界面输入和显示结果。具体界面设计和数据库内容请自由发挥。
参考
代码
- JDBCUtils.java
package com.binbla.jdbc;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
/**
* >Author: BinBla
* >ProjectName myTestJavaProject
* >packageName com.binbla.jdbc
* >Date 12/4/20
*/
public class JDBCUtils {
private static String url,username,password;
static {
InputStream inputStream= JDBCUtils.class.getClassLoader().getResourceAsStream("db.properties");
Properties properties=new Properties();
try {
properties.load(inputStream);
String driver = properties.getProperty("driver");
url = properties.getProperty("url");
username = properties.getProperty("username");
password = properties.getProperty("password");
// 加载驱动
Class.forName(driver);
} catch (Exception e) {
e.printStackTrace();
}
}
// 获取连接对象
public static Connection getConnection(){
try {
return DriverManager.getConnection(url,username,password);
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
}
- db.properties
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://192.168.50.150:3306/myJavaTest
username=myJavaTest
password=tBSdnazE46rWyLJ
- JDBC.java
package com.binbla.jdbc;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Objects;
/**
* >Author: BinBla
* >ProjectName myTestJavaProject
* >PackageName com.binbla.jdbc
* >Date 12/6/20
* 关于JTable https://blog.csdn.net/xietansheng/article/details/78079806
*/
public class JDBCGui extends JFrame implements ActionListener {
JScrollPane tablePane, centerTablePane, southPanel;// 用来显示表格的容器
Object[] name;// 列名
Object[][] valueObjects, centerValueObject;// 列数据
JPanel northPanel, northRightButtonPanel, northRightButtonPanelHead, northRightButtonPanelSon, centerPanel, centerRightButtonPanel;
JTable northTable, centerTable;
JButton[] updateButton, deleteButton;
JButton insertButton, selectButton, getDataButton;
JTextArea console;
Connection connection;
Statement statement;
ResultSet resultSet;
JDBCGui(String name) {
super(name);
init();
}
private void init() {
//初始化
initNorthPanel();
initCenterPanel();
initSouthPanel();
getContentPane().add(northPanel, BorderLayout.NORTH);
getContentPane().add(centerPanel, BorderLayout.CENTER);
getContentPane().add(southPanel, BorderLayout.SOUTH);
//布置面板
pack();
setVisible(true);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
validate();
checkConnection();
}
private void initNorthPanel() {
//上半部分布局
northPanel = new JPanel(new BorderLayout());
name = new Object[]{"ID", "NAME", "CLASS", "SCORE"};
valueObjects = new Object[5][4];
northTable = new JTable(valueObjects, name);
northTable.setRowHeight(20);
tablePane = new JScrollPane(northTable);
tablePane.setPreferredSize(new Dimension(400, 100));
northTable.getTableHeader().setReorderingAllowed(false);//不可拖动表头
northTable.getTableHeader().setResizingAllowed(false);//不可头间拖动来调整各列的大小
northPanel.add(tablePane, BorderLayout.WEST);//添加左边表
northRightButtonPanel = new JPanel();
northRightButtonPanel.setLayout(new BorderLayout());
northRightButtonPanel.setPreferredSize(new Dimension(120, 124));
getDataButton = new JButton("获取表单");
getDataButton.setSize(1200, 20);
getDataButton.addActionListener(this);
getDataButton.setActionCommand("o0");
northRightButtonPanelHead = new JPanel(new GridLayout(1, 1));
northRightButtonPanelHead.add(getDataButton);
northRightButtonPanelHead.setPreferredSize(new Dimension(120, 21));//设置获取表单按钮的高度
northRightButtonPanel.add(northRightButtonPanelHead, BorderLayout.NORTH);
northRightButtonPanelSon = new JPanel(new GridLayout(5, 2));
updateButton = new JButton[5];
deleteButton = new JButton[5];
for (int i = 0; i < 5; ++i) {
updateButton[i] = new JButton("更新");
updateButton[i].setActionCommand("u" + i);
updateButton[i].addActionListener(this);
northRightButtonPanelSon.add(updateButton[i]);
deleteButton[i] = new JButton("删除");
deleteButton[i].setActionCommand("d" + i);
deleteButton[i].addActionListener(this);
northRightButtonPanelSon.add(deleteButton[i]);
}
northRightButtonPanel.add(northRightButtonPanelSon, BorderLayout.CENTER);//添加更新和删除面板
northPanel.add(northRightButtonPanel, BorderLayout.EAST);//把右边的按钮添加进面板
}
private void initCenterPanel() {
//中间部分布局
centerPanel = new JPanel(new BorderLayout());
centerValueObject = new Object[1][4];
centerTable = new JTable(centerValueObject, name);
centerTable.setRowHeight(20);
centerTablePane = new JScrollPane(centerTable);
centerTablePane.setPreferredSize(new Dimension(400, 44));
centerTable.getTableHeader().setReorderingAllowed(false);//不可拖动表头
centerTable.getTableHeader().setResizingAllowed(false);//不可头间拖动来调整各列的大小
centerPanel.add(centerTablePane, BorderLayout.WEST);
centerRightButtonPanel = new JPanel();
centerRightButtonPanel.setLayout(new GridLayout(1, 2));
selectButton = new JButton("查询");
selectButton.setActionCommand("s0");
selectButton.addActionListener(this);
insertButton = new JButton("插入");
insertButton.setActionCommand("i0");
insertButton.addActionListener(this);
centerRightButtonPanel.add(selectButton);
centerRightButtonPanel.add(insertButton);
centerPanel.add(centerRightButtonPanel, BorderLayout.EAST);
}
private void initSouthPanel() {
//下面板布局
console = new JTextArea();
console.setRows(7);
console.setEditable(false);
console.setBackground(Color.pink);
southPanel = new JScrollPane(console);
}
private void updateTable(String s) {//查
//查询语句
if (checkConnection()) {
cleanNorthTable();//清空表格
try {
resultSet = statement.executeQuery(s);
int i = 0;
while (resultSet.next() && i < 5) {
int j = 0;
northTable.getModel().setValueAt(resultSet.getString("id"), i, j++);
northTable.getModel().setValueAt(resultSet.getString("uname"), i, j++);
northTable.getModel().setValueAt(resultSet.getString("class"), i, j++);
northTable.getModel().setValueAt(resultSet.getInt("score"), i, j);
++i;
}
northTable.repaint();
} catch (SQLException e) {
console.append(e.toString());
}
}
}
private void updateServer(String str) {
//执行插入、更新、删除语句
if (checkConnection()) {
try {
statement.execute(str);
console.append("语句已执行");
} catch (SQLException e) {
console.append(e.toString() + "\n");
}
}
northTable.repaint();
}
private String buildStatement(int i, JTable tag, int op) {
// 构造mysql语句
String str = "";
Object id = tag.getModel().getValueAt(i, 0);
Object uname = tag.getModel().getValueAt(i, 1);
Object classID = tag.getModel().getValueAt(i, 2);
Object score = tag.getModel().getValueAt(i, 3);
if (id != null) {
id = id.toString();
}
if (uname != null) {
uname = uname.toString();
}
if (classID != null) {
classID = classID.toString();
}
if (score != null) {
score = score.toString();
}
switch (op) {
case 0:
str = "update `student` set `uname`='" + uname + "',class='" + classID + "',score='" + score + "' where student.id='" + id + "'";
break;//增
case 1:
str = "delete from student where id='" + id + "'";
break;//删
case 2:
str = "select * from student where ";
boolean start = true;
if (id != null && !Objects.equals(id, "")) {
str += "id='" + id + "'";
start = false;
}
if (uname != null && !Objects.equals(uname, "")) {
if (!start) {
str += " and ";
}
str += "uname='" + uname + "'";
start = false;
}
if (classID != null && !Objects.equals(classID, "")) {
if (!start) {
str += " and ";
}
str += "class='" + classID + "'";
start = false;
}
if (score != null && !Objects.equals(score, "")) {
if (!start) {
str += " and ";
}
str += "score='" + score + "'";
start = false;
}
if (start) {
return "";
}
break;//改
case 3:
str = "insert into student(id,uname,class,score) values('" + id + "','" + uname + "','" + classID + "','" + score + "')";
break;//查
}
console.append(str + "\n");
return str;
}
private void cleanNorthTable(){
for(int i=0;i<5;++i){
for(int j=0;j<4;++j){
northTable.getModel().setValueAt(null,i,j);
}
}
northTable.repaint();
}
private boolean checkConnection() {
// 验证和连接数据库
if (connection == null) {
console.append("正在尝试验证数据库账户和密码...\n");
try {
connection = JDBCUtils.getConnection();
console.append("验证成功\n");
} catch (Exception e) {
console.append(e.toString());
console.append("验证失败\n");
return false;
}
}
if (statement == null) {
console.append("正在尝试建立与数据库的连接...\n");
try {
statement = connection.createStatement();
console.append("连接成功\n");
} catch (Exception e) {
console.append(e.toString());
console.append("连接失败\n");
return false;
}
}
return true;
}
@Override
public void actionPerformed(ActionEvent actionEvent) {
// 按钮的监视器操作
String commands = actionEvent.getActionCommand();
char[] action = commands.toCharArray();
int tag = Integer.parseInt(commands.replaceAll("[udiso]", ""));
switch (action[0]) {
case 'u'://更新
updateServer(buildStatement(tag, northTable, 0));
break;
case 'd'://删除
updateServer(buildStatement(tag, northTable, 1));
break;
case 's'://查询
updateTable(buildStatement(tag, centerTable, 2));
break;
case 'i'://插入
updateServer(buildStatement(tag, centerTable, 3));
break;
case 'o'://获取
updateTable("select * from student");
break;
}
}
public static void main(String[] args) {
new JDBCGui("java_6");
}
}