Creating a Java Project
Adding Required Dependencies
Create a lib directoyr in your project and place the necessary JAR files. The required libraries are available for download.
Implementing Database Helper
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class DatabaseConnector {
static {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
} catch (Exception e) {
e.printStackTrace();
}
}
public static Connection getConnection() {
Connection connection = null;
try {
connection = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/db_stu", "root", "123456"
);
} catch (Exception e) {
e.printStackTrace();
}
return connection;
}
public static void closeResources(Connection conn, PreparedStatement ps, ResultSet rs) {
try {
if (conn != null && !conn.isClosed()) {
conn.close();
}
if (ps != null) {
ps.close();
}
if (rs != null) {
rs.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
This class manages database connections using MySQL 8.2 JDBC driver.
Defining Entity and Data Access Object
Only the DAO implementation is shown here:
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
public class StudentDAO {
public List<Student> findAll() {
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
List<Student> students = new ArrayList<>();
try {
connection = DatabaseConnector.getConnection();
statement = connection.prepareStatement("SELECT * FROM tb_stu");
resultSet = statement.executeQuery();
while (resultSet.next()) {
students.add(new Student(
resultSet.getInt(1),
resultSet.getString(2),
resultSet.getString(3),
resultSet.getInt(4)
));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
DatabaseConnector.closeResources(connection, statement, resultSet);
}
return students;
}
public int deleteById(int studentId) {
Connection connection = null;
PreparedStatement statement = null;
try {
connection = DatabaseConnector.getConnection();
statement = connection.prepareStatement("DELETE FROM tb_stu WHERE sid = ?");
statement.setInt(1, studentId);
return statement.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
DatabaseConnector.closeResources(connection, statement, null);
}
return 0;
}
public int insert(Student student) {
Connection connection = null;
PreparedStatement statement = null;
try {
connection = DatabaseConnector.getConnection();
statement = connection.prepareStatement(
"INSERT INTO tb_stu(sid, sname, ssex, sage) VALUES (?, ?, ?, ?)"
);
statement.setInt(1, student.getId());
statement.setString(2, student.getName());
statement.setString(3, student.getGender());
statement.setInt(4, student.getAge());
return statement.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
DatabaseConnector.closeResources(connection, statement, null);
}
return 0;
}
}
Exporting Data from MySQL to Excel
Creating Export Implementation
Initialize the workbook and create a sheet to hold data.
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileOutputStream;
import java.util.List;
public class ExportToExcel {
public static void main(String[] args) {
StudentDAO dao = new StudentDAO();
try (Workbook workbook = new XSSFWorkbook();
FileOutputStream output = new FileOutputStream("C:\\Users\\fujie\\Desktop\\student_data.xlsx")) {
Sheet sheet = workbook.createSheet("Students");
List<Student> students = dao.findAll();
Row headerRow = sheet.createRow(0);
headerRow.createCell(0).setCellValue("ID");
headerRow.createCell(1).setCellValue("Name");
headerRow.createCell(2).setCellValue("Gender");
headerRow.createCell(3).setCellValue("Age");
for (int i = 0; i < students.size(); i++) {
Student student = students.get(i);
Row dataRow = sheet.createRow(i + 1);
dataRow.createCell(0).setCellValue(student.getId());
dataRow.createCell(1).setCellValue(student.getName());
dataRow.createCell(2).setCellValue(student.getGender());
dataRow.createCell(3).setCellValue(student.getAge());
}
workbook.write(output);
System.out.println("Data exported successfully");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Importing Data from Excel to MySQL
Creating Import Implementation
Process Excel rows and convert types appropriately.
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileInputStream;
public class ImportFromExcel {
public static void main(String[] args) {
StudentDAO dao = new StudentDAO();
try (FileInputStream input = new FileInputStream("C:\\Users\\fujie\\Desktop\\student_data.xlsx")) {
XSSFWorkbook workbook = new XSSFWorkbook(input);
XSSFSheet sheet = workbook.getSheetAt(0);
for (Row row : sheet) {
if (row.getRowNum() == 0) continue; // Skip header row
Cell nameCell = row.getCell(1);
Cell genderCell = row.getCell(2);
if (nameCell != null) {
nameCell.setCellType(CellType.STRING);
}
if (genderCell != null) {
genderCell.setCellType(CellType.STRING);
}
int id = (int) row.getCell(0).getNumericCellValue();
String name = nameCell.getStringCellValue();
String gender = genderCell.getStringCellValue();
int age = (int) row.getCell(3).getNumericCellValue();
Student student = new Student(id, name, gender, age);
dao.deleteById(id);
dao.insert(student);
System.out.println("Record inserted successfully");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}