Java实现海量数据的插入需要使用到数据库和相关的操作,以下是一个简单的Java代码实现大量数据插入的示例:
import java.sql.*;
public class InsertData {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/testdb";
static final String USER = "testuser";
static final String PASS = "testpass";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
stmt = conn.createStatement();
String sql = "INSERT INTO Employee " +
"VALUES (100, 'John', 'Doe', '1980-01-01')";
stmt.executeUpdate(sql);
sql = "INSERT INTO Employee " +
"VALUES (101, 'Jane', 'Doe', '1986-12-31')";
stmt.executeUpdate(sql);
sql = "INSERT INTO Employee " +
"VALUES (102, 'Bob', 'Smith', '1970-05-12')";
stmt.executeUpdate(sql);
sql = "INSERT INTO Employee " +
"VALUES(103, 'Tom', 'Jones', '1950-11-12')";
stmt.executeUpdate(sql);
System.out.println("Records inserted successfully.");
} catch(SQLException se) {
se.printStackTrace();
} catch(Exception e) {
e.printStackTrace();
} finally {
try {
if(stmt!=null)
conn.close();
} catch(SQLException se) {
}
try {
if(conn!=null)
conn.close();
} catch(SQLException se) {
se.printStackTrace();
}
}
}
}
这个示例连接到一个名为testdb的MySQL数据库,然后在Employee表中插入四条记录。在实际的应用程序中,可以使用循环和批量插入的技术来插入大量的数据。