2011-09-07 83 views
1

我想動態地插入到mysql數據庫。但我總是隻能看到數據庫中的當前記錄..它不是一個接一個地追加到特定列中......它只是替換以前的條目......我必須在添加每個數據後進行某種提交數據庫?我認爲它會自動執行自動提交?動態使用JAVA插入到MySql數據庫

if (m.find() && thirdentry.startsWith("LO")) { 
    Connection conn = null; 
     Statement s = null; 
     PreparedStatement ps = null; 

     try 
     { 

     conn = DriverManager.getConnection 
     ("jdbc:mysql://localhost/?user=root&password=admin"); 
     s=conn.createStatement(); 

     s.executeUpdate("CREATE DATABASE IF NOT EXISTS crawler"); 
     s.executeUpdate("USE crawler"); 

     s.executeUpdate ("DROP TABLE IF EXISTS crawl"); 

     s.executeUpdate (
     "CREATE TABLE crawl (" 
     + "id INT UNSIGNED NOT NULL AUTO_INCREMENT," 
     + "PRIMARY KEY (id)," 
     + "url VARCHAR(125), timestamp DATETIME, response TEXT, chksum TEXT)"); 


     java.util.Date date= new java.util.Date(); 

    //I always see only the current record.. not the full record 
     ps = conn.prepareStatement (
     "INSERT INTO crawl (url, timestamp, response, chksum) VALUES(?,?,?,?)"); 
     ps.setString (1, url1.toString()); 
     ps.setString (2, new Timestamp(date.getTime()).toString()); 
     ps.setString (3, status); 
     ps.setString (4, hash); 
     int count = ps.executeUpdate(); 
     s.close(); 
     ps.close(); 

     System.out.println (count + " rows were inserted"); 
    } 
catch (Exception e) 
    { 
     System.err.println ("Cannot connect to database server" +e.getMessage()); 
    } 
     finally 
     { 
    if (conn != null) 
      { 
       try 
      { 
       conn.close(); 
       System.out.println ("Database connection terminated"); 
                 } 
        catch (Exception e) { /* ignore close errors */ } 
                } 
               } 
+2

嗯? 's.executeUpdate(「DROP TABLE IF EXISTS crawl」);'會一直刪除你的表,你會在執行結束時看到最新版本的'crawl'表。 –

+0

每次調用此函數時,都會丟棄並創建一個新表。它如何具有以前的價值? –

+0

@all ...我的壞...我正在測試某種方式通過放下桌子...而當我開始真正運行..我忘了刪除DROP表部分... – ferhan

回答

5

您正在丟棄表格並在您每次運行應用程序時重新創建它。在應用程序外創建一次,然後讓應用程序對其進行更新。

+0

,我的壞...我正在測試以某種方式放棄桌子......而當我開始真正運行..我忘了刪除DROP桌子部分...... – ferhan