动态地使用JAVA插入MySql数据库

时间:2011-09-07 21:11:21

标签: java mysql jdbc

我试图动态地插入到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 */ }
                                                    }
                                                }

1 个答案:

答案 0 :(得分:5)

每次运行应用程序时,您都会丢弃表并重新创建它。在应用外部创建一次,让应用更新它。