MySQLへのJDBC接続
JavaアプリケーションからMySQLデータベースに接続するには、JDBCドライバーの設定が必要です。
JDBCドライバーの準備
- MySQL公式サイトからConnector/Jをダウンロードします。
- プロジェクトにライブラリフォルダ(例: lib)を作成し、ダウンロードしたJARファイルを配置します。
- IDEでプロジェクトのビルドパスにJARファイルを追加します。
データベース接続クラスの実装
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DatabaseConnector {
private static Connection connection;
static {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/your_database";
String user = "your_username";
String password = "your_password";
connection = DriverManager.getConnection(url, user, password);
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
public static Connection getConnection() {
return connection;
}
public static void closeConnection() {
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
接続テスト
public class ConnectionTest {
public static void main(String[] args) {
Connection conn = DatabaseConnector.getConnection();
if (conn != null) {
System.out.println("データベース接続成功");
DatabaseConnector.closeConnection();
} else {
System.out.println("接続失敗");
}
}
}
データのExcelエクスポート
Apache POIライブラリを使用してデータベースのデータをExcelファイルにエクスポートします。
Excel出力ユーティリティクラス
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
public class ExcelExporter {
public static Workbook createWorkbook(String sheetName,
String[] headers,
List dataRows) {
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet(sheetName);
// ヘッダー行の作成
Row headerRow = sheet.createRow(0);
CellStyle headerStyle = workbook.createCellStyle();
headerStyle.setAlignment(HorizontalAlignment.CENTER);
for (int i = 0; i < headers.length; i++) {
Cell cell = headerRow.createCell(i);
cell.setCellValue(headers[i]);
cell.setCellStyle(headerStyle);
}
// データ行の追加
for (int rowIndex = 0; rowIndex < dataRows.size(); rowIndex++) {
Row dataRow = sheet.createRow(rowIndex + 1);
String[] rowData = dataRows.get(rowIndex);
for (int colIndex = 0; colIndex < rowData.length; colIndex++) {
dataRow.createCell(colIndex).setCellValue(rowData[colIndex]);
}
}
return workbook;
}
public static void saveToFile(Workbook workbook, String filePath) throws IOException {
try (FileOutputStream outputStream = new FileOutputStream(filePath)) {
workbook.write(outputStream);
}
}
}
データ取得とExcel生成の統合例
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class DataExportService {
public void exportToExcel() {
List records = new ArrayList<>();
try (Connection conn = DatabaseConnector.getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM products")) {
ResultSetMetaData metaData = rs.getMetaData();
int columnCount = metaData.getColumnCount();
// 列名を取得
String[] headers = new String[columnCount];
for (int i = 1; i <= columnCount; i++) {
headers[i-1] = metaData.getColumnName(i);
}
// データを取得
while (rs.next()) {
String[] row = new String[columnCount];
for (int i = 1; i <= columnCount; i++) {
row[i-1] = rs.getString(i);
}
records.add(row);
}
// Excelファイルの生成
Workbook workbook = ExcelExporter.createWorkbook("製品データ", headers, records);
ExcelExporter.saveToFile(workbook, "products_export.xlsx");
} catch (SQLException | IOException e) {
e.printStackTrace();
}
}
}
Webアプリケーションでの実装
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
public class ExportController {
public void handleExportRequest(HttpServletResponse response) throws IOException {
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setHeader("Content-Disposition", "attachment; filename=export.xlsx");
DataExportService exportService = new DataExportService();
// 実際の実装ではデータ取得ロジックをここに追加
try (OutputStream out = response.getOutputStream()) {
// Workbookを生成して出力ストリームに書き込み
// workbook.write(out);
}
}
}