我有一個關於我正在運行的代碼的問題。它意味着根據從SQL數據庫檢索到的變量的值更新顯示。當我運行代碼並向表中插入另一個條目時,循環打印表的值不會改變。我不確定是因爲表中的指針沒有移動,或者是因爲代碼不允許動態更新。當我終止代碼並重新運行新數據時顯示。我正在使用eclipse。在查詢之間更新SQL數據庫?
import java.awt.Graphics;
import javax.swing.JFrame;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Tutorial1 extends JFrame
{
static String State;
public Tutorial1()
{
setTitle("Tutorial1");
setSize(900, 900);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void paint(Graphics g)
{
if (State.equals("0"))
{
g.drawRect(480, 480, 200, 100);
}
if (State.equals("1"))
{
g.fillRect(240, 240, 200, 100);
}
}
public static void main(String[] args)
{
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
new com.mysql.jdbc.Driver();
Class.forName("com.mysql.jdbc.Driver").newInstance();
String connectionUrl = "jdbc:mysql://localhost:3306/capstone";
String connectionUser = "root";
String connectionPassword = "root";
conn = DriverManager.getConnection(connectionUrl, connectionUser, connectionPassword);
stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
rs = stmt.executeQuery("SELECT id,Name,State FROM Sensors ORDER BY id DESC");
{
while (rs.next()) {
Tutorial1 t = new Tutorial1();
//t.paint(null);
while (true)
{
rs.refreshRow();
rs.updateRow();
String id = rs.getString("id");
String Name = rs.getString("Name");
State = rs.getString("State");
System.out.println("ID: " + id + ",Name: " + Name
+ ", State: " + State);
id = "id+1";
System.out.println("Success");
System.out.println(State);
t.repaint();
}
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
//try { if (rs != null) rs.close(); } catch (SQLException e) { e.printStackTrace(); }
// try { if (stmt != null) stmt.close(); } catch (SQLException e) { e.printStackTrace(); }
//try { if (conn != null) conn.close(); } catch (SQLException e) { e.printStackTrace(); }
}
}
}
如果您指的是while(true)循環沒有更新值,那麼這是正確的行爲,因爲結果已經從數據庫中檢索到。如果您需要數據庫的新結果,則需要再次查詢數據庫。 –
那個'真的'看起來會瘋狂地旋轉。你真的應該扼殺它,否則你可能會有數千個重新排列的舊數據重新排列。 – tadman
@tadman什麼會是一個有效的方法來節制循環執行每10秒? –