就像标题所说的那样,我想搜索SQL数据库并使用keyReleased
上的jTextField在JTable上显示它。
这就是我尝试过的:
private void jTextField2KeyReleased(java.awt.event.KeyEvent evt) {
try{
int get = (int)jTable2.getModel().getValueAt(jTable2.getSelectedRow(), 0);
String query = "SELECT FName FROM roominfo WHERE FName LIKE '%" + jTextField2.getText() + "%'";
String url = "jdbc:mysql://localhost:3306/adv";
Connection conn = DriverManager.getConnection(url,"root","sa");
Statement st = conn.createStatement();
rs = st.executeQuery(query);
jTable2.setModel(DbUtils.resultSetToTableModel(rs));
conn.close();
}
catch (Exception e) {
System.err.println("Got an exception! ");
JOptionPane.showMessageDialog(null,"Got an exception!");
System.err.println(e.getMessage());
} // TODO add your handling code here:
}
但是,我不能正确地做到这一点。什么似乎是问题?它仍然没有搜索。
答案 0 :(得分:2)
在keyPressed
:
try{
String url = "jdbc:mysql://localhost:3306/adv";
Connection conn = DriverManager.getConnection(url,"root","sa");
Statement st = conn.createStatement();
String query = "SELECT CustomerNo, FName, FROM roominfo WHERE FName LIKE '%" + jTextField2.getText() + "%'";
rs = st.executeQuery(query);
jTable2.setModel(DbUtils.resultSetToTableModel(rs));
conn.close();
}
catch (Exception e) {
JOptionPane.showMessageDialog(null,"Got an exception!");
System.err.println(e.getMessage());
}
答案 1 :(得分:0)
下载rs2xml.jar库并将其导入到您的特定项目库中。
然后在特定的Java类中import net.proteanit.sql.DbUtils;
。
有一个名为学生的数据库表,当我们在txtId
内插入id值,然后单击创建的search
按钮进行操作时。特定学生ID的行数据将在创建的tableStudent
内部执行。
search
按钮内的代码如下:
String id = txtId.getText();
String searchQuery = "SELECT * FROM student WHERE id ='"+id+"'";
try {
PreparedStatement pst = conn.prepareStatement(searchQuery);
ResultSet rs = pst.executeQuery();
tableStudent.setModel(DbUtils.resultSetToTableModel(rs));
} catch (SQLException ex) {
Logger.getLogger(UpdateDonor.class.getName()).log(Level.SEVERE, null, ex);
}