2011-09-07 81 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