在java中如何从多个run()方法将记录INSERT到数据库中?

时间:2015-01-29 12:25:18

标签: java multithreading jdbc

在我的项目中,我使用多个run()方法。

在每个run()方法中,我得到一个值所以我想将该值插入到oracle DB中。

我在每次运行中都编写了DB插入代码()。但它只存储了第一个run()方法值,其余的run()方法值未插入。

所以请给我建议从多个线程值将值存储到数据库中。

1 个答案:

答案 0 :(得分:0)

首先,您的问题不是很清楚,但下面是测试您案例的示例程序: 关键点: 1.检查是否可以根据线程数使用具有某个池大小的数据库连接池。 2.提交您的更改 3.关闭你的连接。     公共类MultithreadDatabaseEntry     {

   public static void main(String[] args)
   {
      new Thread(new DBJob()).start();
      new Thread(new DBJob()).start();

   }

   public static class DBJob implements Runnable
   {
      public DBJob()
      {
      }

      @Override
      public void run()
      {
         Connection conn = null;
         Statement stmt = null;

         try
         {
            conn = getConnection();
            if(conn != null)
            {
               //Do your database operation
            }


         }
         catch (SQLException e)
         {
            // TODO Auto-generated catch block
            e.printStackTrace();
         }
         finally{
            //finally block used to close resources
            try{
               if(stmt!=null)
                  stmt.close();
            }catch(SQLException se2){
            }// nothing we can do
            try{
               if(conn!=null)
                  conn.commit();
                  conn.close();
            }catch(SQLException se){
               se.printStackTrace();
            }//end finally try
         }//

      }

   }

   //Here you can use different database connection pooling mechanism from Apache DBCP, Tomcat Pool etc
   public static Connection getConnection() throws SQLException
   {
      Connection conn = null;
      Statement stmt = null;
      try{

         Class.forName("com.mysql.jdbc.Driver");


         System.out.println("Connecting to database...");
         conn = DriverManager.getConnection(DB_URL, USER, PASS);


      }
      catch(Exception e)
      {
         //Handle errors for Class.forName
         e.printStackTrace();
      }
      return conn;

   }
}