使用JAVA动态插入MySql数据库 [英] Insert into MySql Database using JAVA dynamically

查看:185
本文介绍了使用JAVA动态插入MySql数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试动态插入mysql数据库.但是我总是只看到数据库中的当前记录..它没有一个接一个地追加到特定的列中..它只是替换了先前的记录...在将每个数据添加到其中之后,我必须进行某种提交数据库?我认为它会自动执行自动提交?

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??

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 */ }
                                                    }
                                                }

推荐答案

您将在每次运行应用程序时删除表并重新创建它.在应用程序外部创建一次,然后让应用程序对其进行更新.

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.

这篇关于使用JAVA动态插入MySql数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆