关于使按钮在 Netbeans 的 GUI 编辑器中工作的 JDBC 到 JTable 输出查询
Posted
技术标签:
【中文标题】关于使按钮在 Netbeans 的 GUI 编辑器中工作的 JDBC 到 JTable 输出查询【英文标题】:JDBC to JTable output query regarding making buttons work in GUI Editor for Netbeans 【发布时间】:2014-11-18 00:57:49 【问题描述】:所以,我正在做一个项目,我必须使用搜索按钮从 jdbc 数据库中查找用户信息,到目前为止,我已经完成了一些代码工作并将字段和数据添加到数据库,但是一旦我在 jtextfield 中点击搜索,它就不会在表中显示任何数据。所以,我想知道是否有人可以看一下这段代码并告诉我错误在哪里,jbutton 应该连接到存储数据库连接信息的大型机。
这是主框架代码:
package guestbook;
import java.sql.Connection;
import java.sql.DriverManager;
public class MainFrame extends javax.swing.JFrame
public static String dbURL = "jdbc:derby://localhost:1527/Coolkidsclub;create=true;user=Vic";
public static Connection conn = null;
/**
* Creates new form MainFrame
*/
public MainFrame()
try
Class.forName("org.apache.derby.jdbc.ClientDriver").newInstance();//"org.apache.derby.jdbc.ClientDriver" to use derby driver
conn = DriverManager.getConnection(dbURL);
initComponents();
catch (Exception e)
initComponents();
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents()
jLabel1 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
jButton4 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/guestbook/ckc.PNG"))); // NOI18N
jButton1.setText("Add Kid");
jButton1.addActionListener(new java.awt.event.ActionListener()
public void actionPerformed(java.awt.event.ActionEvent evt)
jButton1ActionPerformed(evt);
);
jButton2.setText("Update Kid");
jButton2.addActionListener(new java.awt.event.ActionListener()
public void actionPerformed(java.awt.event.ActionEvent evt)
jButton2ActionPerformed(evt);
);
jButton3.setText("Remove Kid");
jButton3.addActionListener(new java.awt.event.ActionListener()
public void actionPerformed(java.awt.event.ActionEvent evt)
jButton3ActionPerformed(evt);
);
jButton4.setText("Find Kid");
jButton4.addActionListener(new java.awt.event.ActionListener()
public void actionPerformed(java.awt.event.ActionEvent evt)
jButton4ActionPerformed(evt);
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(106, 106, 106)
.addComponent(jLabel1)
.addContainerGap(109, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGap(126, 126, 126)
.addComponent(jButton1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton4)
.addGap(130, 130, 130))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton1)
.addComponent(jButton2)
.addComponent(jButton3)
.addComponent(jButton4))
.addContainerGap(44, Short.MAX_VALUE))
);
pack();
// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)
AddFrame add = new AddFrame();
add.setVisible(true);
this.dispose();
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt)
UpdateFrame update = new UpdateFrame();
update.setVisible(true);
this.dispose();
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt)
RemoveFrame remove = new RemoveFrame();
remove.setVisible(true);
this.dispose();
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt)
SearchFrame search = new SearchFrame();
search.setVisible(true);
this.dispose();
public static void main(String args[])
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels())
if ("Nimbus".equals(info.getName()))
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
catch (ClassNotFoundException ex)
java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
catch (InstantiationException ex)
java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
catch (IllegalAccessException ex)
java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
catch (javax.swing.UnsupportedLookAndFeelException ex)
java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable()
public void run()
new MainFrame().setVisible(true);
);
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JButton jButton4;
private javax.swing.JLabel jLabel1;
// End of variables declaration
这是搜索框代码:
package guestbook;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Vector;
import javax.swing.table.DefaultTableModel;
public class SearchFrame extends javax.swing.JFrame
public SearchFrame()
initComponents();
public static DefaultTableModel buildTableModel(ResultSet rs)
throws SQLException
ResultSetMetaData metaData = rs.getMetaData();
Vector<String> columnNames = new Vector<String>();
int columnCount = metaData.getColumnCount();
for (int column = 1; column <= columnCount; column++)
columnNames.add(metaData.getColumnName(column));
Vector<Vector<Object>> data = new Vector<Vector<Object>>();
while (rs.next())
Vector<Object> vector = new Vector<Object>();
for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++)
vector.add(rs.getObject(columnIndex));
data.add(vector);
return new DefaultTableModel(data, columnNames);
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents()
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
jLabel1 = new javax.swing.JLabel();
jTextField1 = new javax.swing.JTextField();
jButton5 = new javax.swing.JButton();
jButton6 = new javax.swing.JButton();
jScrollPane2 = new javax.swing.JScrollPane();
jTable2 = new javax.swing.JTable();
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][]
null, null, null, null,
null, null, null, null,
null, null, null, null,
null, null, null, null
,
new String []
"Title 1", "Title 2", "Title 3", "Title 4"
));
jScrollPane1.setViewportView(jTable1);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/guestbook/fckc.PNG"))); // NOI18N
jTextField1.setText("Type Name Here...");
jButton5.setText("Find Kid");
jButton5.addActionListener(new java.awt.event.ActionListener()
public void actionPerformed(java.awt.event.ActionEvent evt)
jButton5ActionPerformed(evt);
);
jButton6.setText("Go back to Start");
jButton6.addActionListener(new java.awt.event.ActionListener()
public void actionPerformed(java.awt.event.ActionEvent evt)
jButton6ActionPerformed(evt);
);
jTable2.setModel(new javax.swing.table.DefaultTableModel(
new Object [][]
null, null, null, null,
null, null, null, null,
null, null, null, null,
null, null, null, null
,
new String []
"", "", "", ""
));
jTable2.getTableHeader().setReorderingAllowed(false);
jScrollPane2.setViewportView(jTable2);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(113, 113, 113)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 518, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addGroup(layout.createSequentialGroup()
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 383, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton5)))))
.addGroup(layout.createSequentialGroup()
.addGap(294, 294, 294)
.addComponent(jButton6)))
.addContainerGap(146, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton5))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jButton6)
.addContainerGap(58, Short.MAX_VALUE))
);
pack();
// </editor-fold>
private void jButton5ActionPerformed(java.awt.event.ActionEvent evt)
try
Statement stmt = MainFrame.conn.createStatement();
ResultSet rs = stmt.executeQuery("select * from COOLKIDS " + jTextField1.getText().toString());
jTable2.setModel(buildTableModel(rs));//to display the table
catch (Exception except)
private void jButton6ActionPerformed(java.awt.event.ActionEvent evt)
MainFrame main = new MainFrame();
main.setVisible(true);
this.dispose();
/**
* @param args the command line arguments
*/
public static void main(String args[])
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels())
if ("Nimbus".equals(info.getName()))
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
catch (ClassNotFoundException ex)
java.util.logging.Logger.getLogger(SearchFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
catch (InstantiationException ex)
java.util.logging.Logger.getLogger(SearchFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
catch (IllegalAccessException ex)
java.util.logging.Logger.getLogger(SearchFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
catch (javax.swing.UnsupportedLookAndFeelException ex)
java.util.logging.Logger.getLogger(SearchFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable()
public void run()
new SearchFrame().setVisible(true);
);
// Variables declaration - do not modify
private javax.swing.JButton jButton5;
private javax.swing.JButton jButton6;
private javax.swing.JLabel jLabel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JTable jTable1;
private javax.swing.JTable jTable2;
private javax.swing.JTextField jTextField1;
// End of variables declaration
任何帮助将不胜感激,因为我对 java 比较陌生。
编辑:一两天后,我做了一个 stackTrace 异常打印输出,它说明语句 stmt 代码错误,我只需要在 searchframe 中添加一行以连接到数据库并忘记大型机连接吗?
【问题讨论】:
您确实需要尝试在这些示例中删除至少 80% 的代码。只有重复错误所需的代码。 【参考方案1】:所以,我想知道是否有人可以看看这段代码并告诉我错误在哪里,jbutton 应该连接到 存储数据库连接信息的主机。
首先我要说的是代码很多。现在,您的代码中有几个概念性错误可能会导致上述问题。
不要将视图(用户界面)与数据库连接混在一起
请注意,应用程序的设计通常使用层或级别来隔离和分离职责。在这种情况下,在 JFrame
中包含静态 Connection
对象就违反了这一原则。首先要做的是将数据库连接和逻辑与用户界面分开。
不要忽视异常,始终给予正确的处理
这是我们能做的最糟糕的事情之一:
try
...
catch (Exception e)
如果抛出异常,则意味着发生了意外。仅仅忽略一个空的 catch 块中的异常不会使它得到解决,但会向我们隐藏这个事实。因此,我们将无法解决问题,因为我们实际上并不知道发生了什么问题。
避免使用静态引用
如果您需要使用静态来访问类成员,那么可能是我们的代码中存在设计问题。虽然从 OOP 的角度来看,静态字段是可能的并且有时很有用(即:定义常量),但它们不是一个好的选择,因为它违反了封装原则。我们可以通过提供 getter 和 setter 来让外部的类成员访问。
编辑:一两天后,我做了一个 stackTrace 异常打印输出,它说明了语句 stmt 代码错误,我只是 需要在搜索框中添加一行以连接到数据库和 忘记主机连接?
您必须在问题中包含堆栈跟踪,但让我们看一下发送到数据库的 SQL 查询:
ResultSet rs = stmt.executeQuery("select * from COOLKIDS " + jTextField1.getText().toString());
您的 SQL 语句中很可能缺少 WHERE
子句(我不知道从 jTextField1
获得的文本,所以这只是猜测)。 SQL 语句通常具有以下最小结构:
SELECT fields list
FROM tables
WHERE conditions
另一方面,您可以考虑像这样使用PreparedStatement:
String sql = "SELECT * FROM coolkids WHERE name = ?";
PreparedStatement pst = connection.prepareStatement(sql);
pst.setString(1, jTextField1.getText());
ResultSet rs = pst.executeQuery();
同样,此代码应与 UI 隔离,jTextField1
文本应作为参数传递给适当的控制器/持久层类。
【讨论】:
嘿,感谢您回答问题并试图通过在搜索框代码中包含连接代码来帮助我解决问题,以便在按下按钮时打印出整个表格。这可行,但不允许文本字段,所以我只是更改了 GUI 以显示它显示数据库表中的人员列表。我得到的原始代码包括 where 子句,但我不确定 where 子句应该来自哪里。无论如何,我现在对我的编码结果很满意,我很快就会尝试这种方式。谢谢。以上是关于关于使按钮在 Netbeans 的 GUI 编辑器中工作的 JDBC 到 JTable 输出查询的主要内容,如果未能解决你的问题,请参考以下文章
使用 Netbeans 12.2。使用 GUI 设计器我创建了一个按钮。显示我创建的按钮,但是当我运行应用程序时,按钮消失了
如何在 JFXTable 视图中添加按钮编辑和删除以及如何将行编辑到 SQL
Java Netbeans 8.0 Jframe GUI程序 - arraylist中的每个索引值都没有显示在jtextArea中的各行上