阿摩線上測驗 登入

申論題資訊

試卷:113年 - 113 第一銀行_新進人員甄選試題_程式開發人員、資深程式開發人員:A.程式設計(.NET、JAVA+SQL 程式語言為主) B.系統分析 C.資料結構及資料庫應用 #119567
科目:程式設計(以 JAVA、SQL 語言為主)、系統分析、資料結構及資料庫應用
年份:113年
排序:0

題組內容

第二題: 以.NET 或 Java 程式語言完成下列問題:

申論題內容

(二)假設 Student 類別有函式 Connection 可回傳已完成資料庫連線的 SqlConnection 或 DriverManager 之 Connection 物件,請撰寫以參數化查詢新增單筆紀錄的 Add()函式程式碼,並 請基於本大題既有程式碼寫出在主程式新增一筆紀錄的範例。【10 分】

詳解 (共 1 筆)

詳解 提供者:hchungw
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class Student {
    // Method that returns a database connection
    public Connection Connection() {
        // Assume this method returns a valid SqlConnection or DriverManager connection
        // Connection conn = DriverManager.getConnection("jdbc:your_database_url", "username", "password");
        return null; // Placeholder for actual connection
    }
    // Add method to insert a single student record into the database
    public void Add(int id, String name, int age) {
        String sql = "INSERT INTO Students (id, name, age) VALUES (?, ?, ?)";
        try (Connection conn = Connection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            
            // Set the parameters
            pstmt.setInt(1, id);
            pstmt.setString(2, name);
            pstmt.setInt(3, age);
            // Execute the update
            pstmt.executeUpdate();
            System.out.println("Record added successfully.");
        } catch (SQLException e) {
            System.out.println("Error occurred while adding the record: " + e.getMessage());
        }
    }
    public static void main(String[] args) {
        // Create an instance of Student
        Student student = new Student();
        
        // Call Add() to insert a new record
        student.Add(1, "Alice", 22);
    }
}