package
geeksforgeeks;
import
java.sql.Connection;
import
java.sql.DriverManager;
import
java.sql.PreparedStatement;
import
java.sql.SQLException;
public
class
BulkInsertExample {
public
static
void
main(String[] args) {
try
{
Class.forName(
"com.mysql.cj.jdbc.Driver"
);
if
(con !=
null
) {
String insertQuery =
"INSERT INTO book (id, author, name, price) VALUES (?,?, ?, ?)"
;
PreparedStatement preparedStatement = con.prepareStatement(insertQuery);
Object[][] data = {
{
100
,
"Author1"
,
"Book1"
,
"19.99"
},
{
101
,
"Author2"
,
"Book2"
,
"29.99"
},
{
102
,
"Author3"
,
"Book3"
,
"39.99"
}
};
for
(Object[] row : data) {
preparedStatement.setInt(
1
, (
int
) row[
0
]);
preparedStatement.setString(
2
, (String) row[
1
]);
preparedStatement.setString(
3
, (String) row[
2
]);
preparedStatement.setString(
4
, (String) row[
3
]);
preparedStatement.addBatch();
}
int
[] batchResults = preparedStatement.executeBatch();
for
(
int
result : batchResults) {
}
System.out.println(
"Bulk insert completed successfully."
);
}
else
{
System.out.println(
"Not Connected..."
);
}
}
catch
(ClassNotFoundException | SQLException e) {
System.out.println(
"Exception is "
+ e.getMessage());
}
}
}