import java.io.FileReader;
import com.opencsv.CSVReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class CSVImporter {
public static void main(String[] args) {
String csvFile = "data.csv";
String jdbcURL = "jdbc:mysql://localhost:3306/mydatabase";
String username = "root";
String password = "password";
try (CSVReader reader = new CSVReader(new FileReader(csvFile));
Connection connection = DriverManager.getConnection(jdbcURL, username, password)) {
String[] nextLine;
String insertQuery = "INSERT INTO mytable (column1, column2, column3) VALUES (?, ?, ?)";
PreparedStatement preparedStatement = connection.prepareStatement(insertQuery);
while ((nextLine = reader.readNext()) != null) {
preparedStatement.setString(1, nextLine[0]);
preparedStatement.setString(2, nextLine[1]);
preparedStatement.setString(3, nextLine[2]);
preparedStatement.executeUpdate();
}
System.out.println("CSV data imported successfully!");
} catch (Exception e) {
e.printStackTrace();
}
}
}
<dependency>
<groupId>com.opencsv</groupId>
<artifactId>opencsv</artifactId>
<version>5.5.2</version>
</dependency>