- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个从数据库填充的 JTable
。我正在使用自定义模型 ResultSetTableModel
。以下是定制模型:
public class ResultSetTableModel extends AbstractTableModel {
private String[] columnNames;
private Class[] columnClasses;
private List<List<Object>> cells = new ArrayList<List<Object>>();
public ResultSetTableModel() {
columnNames = new String[1];
columnNames[0] = "Result Set";
List<Object> row = new ArrayList<Object>();
row.add("No data");
cells.add(row);
}
public ResultSetTableModel(ResultSet rs) throws SQLException {
ResultSetMetaData rsmd = rs.getMetaData();
// SOMETHING TO KEEP AN EYE ON! It looks like the ResultSetMetaData
// object screws up once the ResultSet itself has been read (ie by
// rs.next() ). Putting any rsmd.XXXX commands after the "while" loop at
// the bottom throws a nasty exception. A bug on the SQLite side I
// think.
columnNames = new String[rsmd.getColumnCount()];
for (int i = 1; i <= rsmd.getColumnCount(); i++) {
columnNames[i - 1] = rsmd.getColumnName(i);
}
columnClasses = new Class[rsmd.getColumnCount()];
for (int i = 1; i <= rsmd.getColumnCount(); i++) {
int columnType = rsmd.getColumnType(i);
switch (columnType) {
case java.sql.Types.INTEGER:
case java.sql.Types.NUMERIC:
columnClasses[i - 1] = Integer.class;
break;
case java.sql.Types.VARCHAR:
case java.sql.Types.CHAR:
case java.sql.Types.DATE:
columnClasses[i - 1] = String.class;
break;
case java.sql.Types.DECIMAL:
case java.sql.Types.FLOAT:
columnClasses[i - 1] = Float.class;
default:
columnClasses[i - 1] = Object.class;
break;
}
}
while (rs.next()) {
List<Object> row = new ArrayList<Object>();
for (int i = 1; i <= rsmd.getColumnCount(); i++) {
row.add(rs.getString(i));
}
cells.add(row);
}
}
public int getRowCount() {
return cells.size();
}
public int getColumnCount() {
return columnNames.length;
}
@Override
public Class getColumnClass(int columnIndex) {
if (columnClasses != null) {
return columnClasses[columnIndex];
} else {
return Object.class;
}
}
public boolean isEmpty() {
return cells.isEmpty();
}
public Object getValueAt(int rowIndex, int columnIndex) {
return cells.get(rowIndex).get(columnIndex);
}
@Override
public String getColumnName(int columnIndex) {
return columnNames[columnIndex];
}
public void deleteRowDisplay(int index) {
this.cells.remove(index);
}
public void deleteRow(String username, String query, int indexOndisplay) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager
.getConnection("jdbc:mysql://localhost:3306/quotgen",
"root", "3498140591");
Statement statement = connection.createStatement();
statement.executeUpdate(query);
} catch (ClassNotFoundException | SQLException e) {
System.out.println(e.getMessage());
}
this.deleteRowDisplay(indexOndisplay);
this.fireTableRowsDeleted(indexOndisplay, indexOndisplay);
}
}
我的主要类(class)如下:
public class ControlP extends JFrame {
// variables
private static String query = "SELECT code as Code,description as Description, price as Price, quantity"
+ " as Quantity FROM products";
private JTable table;
private JScrollPane sp;
ResultSetTableModel rm;
JButton edit;
JButton add;
ControlP() {
this.initUI();
// button actions
this.edit.addActionListener((ActionEvent) -> {
JDialog editProduct = new JDialog(this,
ModalityType.APPLICATION_MODAL);
editProduct.setTitle("Edit Product");
editProduct.setSize(400, 400);
editProduct.setLayout(new java.awt.BorderLayout());
editProduct.setLocationRelativeTo(this);
final int selectedRow = this.table.getSelectedRow();
EditProductRecord ap = new EditProductRecord(editProduct,
this.table, selectedRow);
editProduct.add(ap);
editProduct.setVisible(true);
editProduct.pack();
});
}
private void initUI() {
this.setSize(600, 600);
this.setVisible(true);
this.setLayout(new BorderLayout(5, 5));
this.setLocationRelativeTo(null);
edit = new JButton("Edit");
add = new JButton("Add");
this.add(edit, BorderLayout.NORTH);
this.add(add, BorderLayout.SOUTH);
// constructing the table here
try {
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager
.getConnection("jdbc:mysql://localhost:3306/quotgen",
"root", "3498140591");
Statement statement = connection.createStatement();
ResultSet result = statement.executeQuery(query);
this.rm = new ResultSetTableModel(result);
this.table = new JTable(rm);
if (!rm.isEmpty()) {
table.setRowSelectionInterval(0, 0);
}
this.sp = new JScrollPane(this.table);
this.add(sp, BorderLayout.CENTER);
} catch (SQLException | ClassNotFoundException ex) {
JOptionPane.showMessageDialog(null, ex.getMessage());
// close connection
}
}
public static void main(String[] args) {
Runnable run = new Runnable() {
@Override
public void run() {
ControlP cp = new ControlP();
}
};
EventQueue.invokeLater(run);
}
}
在这个主类中,我有一个按钮edit
,单击该按钮时将弹出一个JDialog
,其中包含一个JPanel
,其中包含根据要更新的详细信息表中突出显示的行。这是编辑类:
public class EditProductRecord extends JPanel {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/quotgen";
// Database credentials
static final String USER = "root";
static final String PASS = "3498140591";
public EditProductRecord(JDialog dialog, JTable table, int selectedRow) {
this.initUI();
// initialize panel fields
this.codeT.setText((table.getValueAt(selectedRow, 0)).toString());
this.descT.setText((table.getValueAt(selectedRow, 1)).toString());
this.priceT.setText((table.getValueAt(selectedRow, 2)).toString());
this.quantityT.setText((table.getValueAt(selectedRow, 3)).toString());
this.codeT.setEnabled(false);
this.codeT.setToolTipText("You cannot change the product code!");
// /////////////////////////////////////////
this.cancel.addActionListener((ActionEvent) -> {
dialog.dispose();
});
this.save.addActionListener((ActionEvent) -> {
// check that all input fields are not empty!
if (this.descT.getText().equals("")
|| this.priceT.getText().equals("")
|| this.quantityT.getText().equals("")) {
this.emptyField.setVisible(true);
} else {
Connection conn = null;
Statement stmt = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
stmt = conn.createStatement();
String sql = "INSERT INTO products (code, description,price,quantity) "
+ "VALUES ('"
+ this.codeT.getText()
+ "', '"
+ this.descT.getText()
+ "','"
+ this.priceT.getText()
+ "','"
+ this.quantityT.getText()
+ "')"
+ "ON DUPLICATE KEY UPDATE description = '"
+ this.descT.getText()
+ "',price='"
+ this.priceT.getText()
+ "',quantity='"
+ this.quantityT.getText() + "'";
stmt.execute(sql);
JOptionPane.showMessageDialog(dialog, "Done.");
} catch (SQLException se) {
// Handle errors for JDBC
se.printStackTrace();
} catch (Exception e) {
// Handle errors for Class.forName
e.printStackTrace();
} finally {
// finally block used to close resources
try {
if (stmt != null)
conn.close();
} catch (SQLException se) {
}// do nothing
try {
if (conn != null)
conn.close();
} catch (SQLException se) {
se.printStackTrace();
}// end finally try
}// end try
}
});
}
private void initUI() {
// main panel properties
this.setPreferredSize(new Dimension(400, 400));
this.setLayout(new BorderLayout(5, 5));
// dummy panels
JPanel dummyN = new JPanel();
dummyN.setPreferredSize(new Dimension(350, 50));
JPanel dummyS = new JPanel();
dummyS.setPreferredSize(new Dimension(350, 50));
dummyS.setLayout(new net.miginfocom.swing.MigLayout());
JPanel dummyE = new JPanel();
dummyE.setPreferredSize(new Dimension(50, 300));
JPanel dummyW = new JPanel();
dummyW.setPreferredSize(new Dimension(50, 300));
JPanel centerPanel = new JPanel();
centerPanel.setPreferredSize(new Dimension(350, 300));
centerPanel.setLayout(new net.miginfocom.swing.MigLayout());
centerPanel.setBorder(BorderFactory.createTitledBorder("Product"));
this.codeL = new JLabel("Code");
this.codeT = new JTextField(10);
this.descL = new JLabel("Description");
;
this.descT = new JTextField(10);
this.priceL = new JLabel("Price");
;
this.priceT = new JTextField(10);
this.quantityL = new JLabel("Quantity");
;
this.quantityT = new JTextField(10);
emptyField = new JLabel("All fields should have Input!");
emptyField.setForeground(Color.red);
emptyField.setVisible(false);
centerPanel.add(this.codeL);
centerPanel.add(this.codeT, "wrap");
centerPanel.add(this.descL);
centerPanel.add(this.descT, "wrap");
centerPanel.add(this.priceL);
centerPanel.add(this.priceT, "wrap");
centerPanel.add(this.quantityL);
centerPanel.add(this.quantityT, "wrap");
centerPanel.add(emptyField);
this.cancel = new JButton("Cancel");
this.clear = new JButton("Clear");
this.save = new JButton("Save");
JLabel dummy = new JLabel("Dummy");
dummy.setVisible(false);
dummyS.add(dummy);
dummyS.add(this.cancel);
dummyS.add(this.clear);
dummyS.add(this.save);
this.add(centerPanel, BorderLayout.CENTER);
this.add(dummyN, BorderLayout.NORTH);
this.add(dummyS, BorderLayout.SOUTH);
this.add(dummyW, BorderLayout.WEST);
this.add(dummyE, BorderLayout.EAST);
}
// controls
JLabel codeL;
JTextField codeT;
JLabel descL;
JTextField descT;
JLabel priceL;
JTextField priceT;
JLabel quantityL;
JTextField quantityT;
JLabel emptyField;
JButton cancel;
JButton clear;
JButton save;
}
现在一切正常除了在保存编辑的行后更新表中显示的数据。
问题:当我单击保存
来保存编辑时,数据仅发送到数据库,而不是发送到表模型中。
我希望在保存到数据库后,数据也被插入到模型中,并且这也应该反射(reflect)在显示屏上。
问题:我们如何让它按照我上面建议的方式工作?另外添加一行后应该如何发生同样的情况?
我已经尝试过
public void rowInserted(){
this.fireTableDataChanged();
}
插入数据库后调用,但没有解决问题。
最佳答案
您可能可以使用的一种方法是提供一种方法,您可以通过该方法从数据库“更新”TableModel
,仅包括那些已更改的行。
这需要您知道插入/更新的行的“key”或“id”,并仅针对这些值运行 select
查询。然后,您可以通过某种“更新”方法将此 ResultSet
传递给预先存在的 TableModel
,该方法只需加载或更新 ResultSet< 中的行即可
.
这可能需要某种Map
,它以行的“key”或“id”为键,以便您可以更轻松地更新它。
我可能考虑的一件事是提供行数据的 POJO,您不仅可以使用它存储在查找 Map
中,还可以发现指定记录的模型的行索引.
关于java - 将一行插入 ResultTableModel 以及数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29577125/
我有 512 行要插入到数据库中。我想知道提交多个插入内容是否比提交一个大插入内容有任何优势。例如 1x 512 行插入 -- INSERT INTO mydb.mytable (id, phonen
已经提出了类似的问题,但由于它总是取决于,我单独询问我的具体情况。 我有一个网站页面,显示来自数据库的一些数据,要从该数据库生成数据,我必须执行一些相当复杂的多连接查询。 数据每天(每晚)更新一次。
我正在使用 MongoDb 和 MySQL 的 python 连接器 pymongo 和 pymysql 测试 MongoDb 和 MySQL,特别是插入功能。 pymongo版本是3.4,pymys
从 C# 应用程序插入大型数组(10M 元素)的最快方法是什么? 到目前为止,我使用的是批量插入。 C# 应用程序生成一个大文本文件,我使用 BULK INSERT 命令加载它。出于好奇,我编写了一个
我编写了一个枚举类型,当我为它运行我创建的 JUnit 测试时会出现以下语法错误: java.lang.Error: Unresolved compilation problems: Synt
我正在尝试创建一个程序,它将单词列表作为输入,并将它们排序为二叉树,以便能够找到它们,例如像字典。这是我到目前为止所做的,但是 newEl -> el = input; 出现段错误,我知道这是因为它试
你好 我有编译这个问题 \begin{equation} J = \sum_{j=1}^{C} \end{equation} 我不断收到错误 missing $ inserted 这很奇怪,因
我需要使用 LINQ to SQL 将记录插入到没有主键的表中。 table 设计得很差;我无法控制表结构。该表由几个 varchar 字段、一个文本字段和一个时间戳组成。它用作其他实体的审计跟踪。
我正在尝试使用 itextsharp 创建 Pdf。我添加了一张包含两列的表格,其中一列包含文本和其他图像。我想要恒定的图像大小 如果另一个单元格中的文本增加并且其他单元格中的图像大小不同,我的图像会
我想把 calory 作为 fruits 的第一个值,我做不到,有人能帮忙吗? $sql = 'INSERT INTO fruits VALUES('', ?, ?, ?)'
我有一个包含季度观察结果的 data.frame。我现在想插入每月值(首选三次,线性很好)。中间目标应该是使用 DATE 创建一个 data.frame作为所有每月观察的索引和缺失值。 谷歌搜索表明我
我想知道是否有办法在值列表中使用“插入”。我正在尝试这样做: insert into tblMyTable (Col1, Col2, Col3) values('value1', value
我想让人们能够在他们的网站中插入单个 Javascript 行,这实际上允许我插入包含我网站内容的固定大小的 IFRAME。它实际上是一个小部件,允许他们搜索我的网站或接收其他信息。这可能吗? 最佳答
我有一个包含时间的表,列名为 time,数据类型为 Date。 在 asp.net 中,我想要一个查询插入日期,另一个查询则在 2 个日期之间进行选择。 我已经尝试过这个: string data =
这是我的代码: create or replace trigger th after insert on stock for each row declare sqty number;
这是一个带有具体示例的通用问题。 我有一个包含三个字段(流派 ID (PK IDENTITY)、流派和子流派)的表。该表对(流派,子流派)组合具有唯一约束。 我想知道如何修改存储过程以在表中不存在时插
因此,我正在遍历二叉树,节点包含字符串,以及读取文件时该字符串是否出现多次。我只查找读取文件时出现次数最多的前 10 个单词,因此本质上我只是比较 int 值。 我的问题是我正在尝试找出一种有效的方法
我有一张机票和行李 map , 每张门票必须是唯一的,并且必须与 map 上的位置相对应 是否可以仅更改行李(m_bagage->秒)而不更改 key ? std::unordered_map m_c
我正在使用 jdbc 驱动程序做一个示例项目。我的问题是,如果我在 2 文本字段中输入空值。 null 不应该加载到数据库中吗?有没有办法避免在数据库中插入空字段?任何帮助将不胜感激。 //Execu
我想知道 SSIS 中是否有特定的插入或更新选项。 如果我想让程序检查它是更新还是插入,我是否必须做一些编码?或者是否可以启用一个选项,以便它会自行检查 PK 是否存在,然后更新,否则插入? 亲切的问
我是一名优秀的程序员,十分优秀!