CodeGym/Java Course/All lectures for KO purposes/데이터베이스에 개체 저장

데이터베이스에 개체 저장

사용 가능

JDBC 데이터 유형의 전체 목록

알고 있는 데이터 유형 외에도 JDBC를 사용하면 DBMS에 대한 많은 기본 데이터 유형을 사용할 수 있습니다. 아래에 유형과 이를 가져오는 기능을 나열합니다.

유형 방법
정렬 getArray()
AsciiStream getAsciiStream()
BigDecimal getBigDecimal()
바이너리스트림 getBinaryStream()
얼룩 getBlob()
부울 getBoolean()
얼룩 getBlob()
부울 getBoolean()
바이트 getByte()
바이트 getBytes()
캐릭터 스트림 getCharacterStream()
덩어리 getClob()
날짜 getDate()
더블 getDouble()
뜨다 getFloat()
정수 getInt()
getLong()
NCharacterStream getNCharacterStream()
물체 getObject()
참조 getRef()
행 ID getRowId()
짧은 getShort()
SQLXML getSQLXML()
getString()
시간 getTime()
타임스탬프 getTimestamp()
유니코드스트림 getUnicodeStream()
URL getURL()

우리는 이미 기본 유형을 고려했습니다. 이제 객체로 작업해 봅시다.

BLOB 데이터 유형

일부 개체를 데이터베이스에 저장하려는 경우 가장 쉬운 방법은 SQL BLOB 유형을 사용하는 것입니다. JDBC에는 Blob이라는 대응 항목이 있습니다.

BLOB는 Binary L arge Object를 나타 냅니다 . 바이트 배열을 저장하는 데 사용됩니다. JDBC의 Blob 유형은 인터페이스이며 두 가지 방법으로 데이터를 입력(및 수신)할 수 있습니다.

  • InputStream 사용
  • 바이트 배열 사용

예: 열 번호 3에는 BLOB 유형이 포함됩니다.

Statement statement = connection.createStatement();
    ResultSet results = statement.executeQuery("SELECT * FROM user");
    results.first();

    Blob blob = results.getBlob(3);
    InputStream is = blob.getBinaryStream();

고유한 Blob 개체를 만들려면 createBlob() 함수를 사용해야 합니다 . 예:

String insertQuery = “INSERT INTO images(name, image) VALUES (?, ?);
PreparedStatement statement = connection.prepareStatement(insertQuery);

// Create a Blob object and get an OtputStream from it to write data to it
Blob blob = connection.createBlob();

// Populate the Blob with data...
OutputStream os = blob.setBinaryStream(1);

// Passing Blob as query parameter
statement.setBlob(2, blob);
statement.execute();

Blob을 데이터로 채우는 방법에는 두 가지가 있습니다. 첫 번째는 OutputSteam을 통한 것입니다 .

Path avatar = Paths.get("E:\\images\\cat.jpg");
OutputStream os = blob.setBinaryStream(1);
Files.copy(avatar, os);

그리고 두 번째 - 바이트 채우기를 통해:

Path avatar = Paths.get("E:\\images\\cat.jpg");
byte[] content = Files.readAllBytes(avatar);
blob.setBytes(1, content);

데이터베이스에 Java 개체 저장

바이트 배열, 바이트 스트림 등 바이너리 개체를 데이터베이스에 저장하는 방법을 배웠습니다. Java 객체는 어떻습니까? Java 개체를 데이터베이스에 어떻게 저장합니까?

회사 직원을 설명하는 Employee Java 클래스가 있다고 가정해 보겠습니다 .

public class Employee {
    public Integer id;
    public String name;
    public String occupation;
    public Integer salary;
    public Date joinDate;
}

JDBC를 사용하여 이 클래스의 객체를 데이터베이스에 어떻게 저장할 수 있습니까?

사실, 당신은 이미 당신이 알아야 할 모든 것을 알고 있습니다. 먼저 이 클래스에 해당하는 데이터베이스에 테이블을 만들어야 합니다. 예를 들면 다음과 같습니다.

CREATE TABLE employee {
    id INT PRIMARY KEY NOT NULL,
    name VARCHAR(100),
    occupation VARCHAR(100),
    salary INT,
    join_date DATE
}

이제 직원 클래스의 개체를 베이스에 추가하는 코드를 작성해 보겠습니다.

public static boolean addEmployee(Connection connection, Employee employee) throws Exception {
    	// Create and prepare a query to insert data into the table
    	String insertQuery = "INSERT INTO employee(name, occupation, salary, join_date ) VALUES (?, ?, ?, ?)";
    	PreparedStatement statement = connection.prepareStatement(insertQuery);

    	// Populate the query with data from the Employee object
    	statement.setString(1, employee.name);
    	statement.setString(2, employee.occupation);
    	statement.setInt(3, employee.salary);
    	statement.setDate(4, employee.joinDate);

    	// Execute our query and it returns true if a new row has been added
    	int count = statement.executeUpdate();
    	return count > 0;
    }

간단하고 명확합니다. 이 방법은 훌륭하게 작동합니다.

데이터베이스에서 Java 객체 읽기

데이터베이스에 개체를 쓰는 방법을 배웠으니 이제 데이터베이스에서 개체를 읽는 코드를 작성해 보겠습니다. ID로 데이터베이스에서 개체를 읽는 코드부터 시작하겠습니다.

public static Employee getEployeeById(Connection connection, int id) throws Exception {
    	// Create and prepare a query to get an employee from the table
    	PreparedStatement statement = connection.prepareStatement("SELECT * FROM employee WHERE id = ?");
    	statement.setInt(1, id);

    	// Execute our query and it returns null if there are no rows in the query result
    	ResultSet results = statement.executeQuery();
    	if (!results.first())
        	return null;

    	// Populate the Employee object with the data from the ResultSet
    	Employee employee = new Employee();
    	employee.id = results.getInt(1);
    	employee.name = results.getString(2);
    	employee.occupation = results.getString(3);
    	employee.salary = results.getInt(4);
    	employee.joinDate = results.getDate(5);
    	return employee;
}

그리고 하나의 객체가 아니라 여러 객체가 필요하다면? 이러한 요청도 작성하기 쉽습니다. 우리 회사의 모든 직원을 확보합시다.

public static List<Employee> getAllEployees(Connection connection) throws Exception {
	// Create and execute a query to get employees from the table
	Statement statement = connection.createStatement();
	ResultSet results = statement.executeQuery("SELECT * FROM employee");

	ArrayList<Employee> list = new ArrayList<Employee>();
	while (results.next()) {
        // Populate the Employee object with the data from the current row of the ResultSet
	        Employee employee = new Employee();
	        employee.id = results.getInt(1);
	        employee.name = results.getString(2);
	        employee.occupation = results.getString(3);
	        employee.salary = results.getInt(4);
	        employee.joinDate = results.getDate(5);

	        list.add(employee);
	}
	return list;
}

그건 그렇고, 그러한 방법이 많으면 각각에서 ResultSet 문자열 을 객체로 변환하기 위해 동일한 코드를 작성해야합니다직원. 따라서 이 코드는 별도의 메서드로 이동할 수 있습니다.

이는 Employee 클래스 에 Enum, InputStream 또는 데이터베이스에 저장하려는 다른 개체에 대한 참조와 같은 복잡한 필드가 포함된 경우 특히 유용할 수 있습니다 .

코멘트
  • 인기
  • 신규
  • 이전
코멘트를 남기려면 로그인 해야 합니다
이 페이지에는 아직 코멘트가 없습니다