Java Array to Database: JDBC Guide

You can utilize JDBC (Java Database Connectivity) in Java to store data from an array into a database. Below is a simple example code:

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 = "username";
        String password = "password";
        Connection conn = null;

        try {
            conn = DriverManager.getConnection(url, username, password);

            int[] data = {1, 2, 3, 4, 5};

            String query = "INSERT INTO mytable (column_name) VALUES (?)";
            PreparedStatement preparedStatement = conn.prepareStatement(query);

            for (int i = 0; i < data.length; i++) {
                preparedStatement.setInt(1, data[i]);
                preparedStatement.executeUpdate();
            }

            System.out.println("Data inserted successfully");

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

In the example code above, a connection with the database is first established. Then, an integer array named data is defined, and the data in the array is inserted into the database table one by one using PreparedStatement. Finally, the database connection is closed. Please modify the database connection information, table name, and field names according to your actual situation.

bannerAds