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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7340572/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 19:35:11  来源:igfitidea点击:

Insert into MySql Database using JAVA dynamically

javamysqljdbc

提问by arsenal

I am trying to insert into mysql database dynamically. But I always see only current record in the database.. It is not appending into the particular column one after one another.. it just replace the previous entry made... I have to do some sort of commit after each data is added into the database? I think it performs auto commit automatically??

我正在尝试动态插入 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 */ }
                                                    }
                                                }

回答by Paul Tomblin

You're dropping the table and re-creating it every time you run the app. Create it once outside of the app, and let the app update it.

每次运行应用程序时,您都会删除表并重新创建它。在应用程序之外创建一次,然后让应用程序更新它。