How can you store data from an array into a database in Java?
To store data from an array into a database in Java, we typically need to implement it through JDBC (Java Database Connectivity). Below is a simple example code to achieve this functionality:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class ArrayToDatabase {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/mydatabase";
String username = "root";
String password = "password";
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
connection = DriverManager.getConnection(url, username, password);
String sql = "INSERT INTO mytable (column_name) VALUES (?)";
preparedStatement = connection.prepareStatement(sql);
int[] array = {1, 2, 3, 4, 5};
for (int i = 0; i < array.length; i++) {
preparedStatement.setInt(1, array[i]);
preparedStatement.executeUpdate();
}
System.out.println("Data inserted successfully");
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (preparedStatement != null) {
preparedStatement.close();
}
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
In the code above, the first step is to establish a connection with the database, followed by preparing an INSERT statement for data insertion. Then, an integer array is defined, where each element is iterated through in a loop and inserted into the database. Finally, the connection and prepared statement are closed. This is just a simple example, adjustments may be needed based on specific requirements in real scenarios.