2024/6/9

The-rich發表於2024-06-17

今天寫資料庫的實驗五,使用Java寫了一個十分簡易的資料庫,連輸入都沒有,只是證明我用Java連上了sqlserver,程式碼如下:

複製程式碼
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class Main {
    public static void main(String[] args) {
        String url = "jdbc:sqlserver://localhost:1433;databaseName=YourDatabase";
        String user = "username";
        String password = "password";

        try (Connection conn = DriverManager.getConnection(url, user, password)) {
            // 插入資料
            String insertSql = "INSERT INTO students (name, age, gender, class) VALUES (?, ?, ?, ?)";
            try (PreparedStatement insertStmt = conn.prepareStatement(insertSql)) {
                insertStmt.setString(1, "Alice");
                insertStmt.setInt(2, 18);
                insertStmt.setString(3, "Female");
                insertStmt.setString(4, "Class A");
                insertStmt.executeUpdate();
            }

            // 更新資料
            String updateSql = "UPDATE students SET age = ? WHERE name = ?";
            try (PreparedStatement updateStmt = conn.prepareStatement(updateSql)) {
                updateStmt.setInt(1, 20);
                updateStmt.setString(2, "Alice");
                updateStmt.executeUpdate();
            }

            // 刪除資料
            String deleteSql = "DELETE FROM students WHERE name = ?";
            try (PreparedStatement deleteStmt = conn.prepareStatement(deleteSql)) {
                deleteStmt.setString(1, "Alice");
                deleteStmt.executeUpdate();
            }

            // 查詢資料
            String selectSql = "SELECT * FROM students";
            try (PreparedStatement selectStmt = conn.prepareStatement(selectSql);
                 ResultSet rs = selectStmt.executeQuery()) {
                while (rs.next()) {
                    String name = rs.getString("name");
                    int age = rs.getInt("age");
                    String gender = rs.getString("gender");
                    String className = rs.getString("class");
                    System.out.println(name + " - " + age + " - " + gender + " - " + className);
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

相關文章