![](/img/trans.png)
[英]how to insert multiple records from json string into google datastore in java
[英]in java how to INSERT records into database from multiple run() methods?
在我的项目中,我使用了多个run()方法。
在每个run()方法中,我都得到一个值,因此我想将该值插入到oracle DB中。
我在每个run()中都编写了DB插入代码。但是它仅存储第一个run()方法值,其余的run()方法值未插入。
因此,请给我一些建议,以将值从多个线程值存储到数据库中。
首先,您的问题不是很清楚,但是下面是测试您的情况的示例程序:要点: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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.