swing将数据从mysql db检索到textfield

我在mysql表中有列有100条记录,我希望从textfield中的表中显示值(每3秒显示0到99之间的记录)。 这是我的代码:

Connection conn = null; Statement st = null; ResultSet rs = null; String dbUrl = "jdbc:mysql://localhost:3306/jointdb"; String dbUsr = "root"; String dbPass = "a12345"; try{ String sql= "select expert1 from eridb"; Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection (dbUrl,dbUsr,dbPass); st = conn.createStatement(); rs = st.executeQuery(sql); // textField1.setText("enter text here"); while(rs.next()){ //Get values String value = rs.getString("expert1"); textField1.setText(value); } }catch(Exception e){ e.printStackTrace(); }finally{ try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } try { st.close(); } catch (SQLException e) { e.printStackTrace(); } try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } 

现在,我希望从索引0-99记录每3秒显示一次记录值

注意:数据每隔3秒就会进入数据库,谢谢

使用Thread.sleep(毫秒)

 while(rs.next()){ String value = rs.getString("expert1"); textField1.setText(value); try { Thread.sleep(3000); } catch(Exception e) {} } 

您可以使用Thread进行并行处理。

请阅读如何使用Swing Timer和Event Dispatch Thread 。

然后使用javax.swing.Timer重新读取数据库中的数据,并按照您需要的方式在JTextField上设置内容。

 Timer timer = new Timer(3000, new ActionListener() { @Override public void actionPerformed(ActionEvent e) { .... // retrieve data and prepare the textField content textField.setContent(...); } }); timer.start();