โค้ดยิม/หลักสูตรจาวา/All lectures for TH purposes/การบันทึกวัตถุลงในฐานข้อมูล

การบันทึกวัตถุลงในฐานข้อมูล

มีอยู่

รายการประเภทข้อมูล JDBC ที่สมบูรณ์

นอกจากประเภทข้อมูลที่คุณรู้จักแล้ว JDBC ยังให้คุณทำงานกับประเภทข้อมูลเนทีฟจำนวนมากสำหรับ DBMS ด้านล่างฉันจะแสดงรายการประเภทและฟังก์ชันที่จะได้รับ:

พิมพ์ วิธี
อาร์เรย์ getArray()
AsciiStream getAsciiStream()
บิ๊กทศนิยม getBigDecimal()
ไบนารีสตรีม getBinaryStream()
หยด getBlob()
บูลีน รับบูลีน()
หยด getBlob()
บูลีน รับบูลีน()
ไบต์ รับไบต์ ()
ไบต์ รับไบต์ ()
สตรีมตัวละคร รับ CharacterStream()
ก้อน getClob()
วันที่ รับวันที่ ()
สองเท่า รับสองเท่า ()
ลอย getFloat()
นานาชาติ getInt()
ยาว รับยาว ()
N CharacterStream getNCharacterStream()
วัตถุ getObject()
อ้างอิง รับการอ้างอิง ()
รหัสแถว getRowId()
สั้น รับสั้น ()
SQLXML getSQLXML()
สตริง getString()
เวลา รับเวลา ()
การประทับเวลา รับการประทับเวลา ()
ยูนิโค้ดสตรีม getUnicodeStream()
URL รับ URL()

เราได้พิจารณาประเภทดั้งเดิมแล้ว ตอนนี้ลองทำงานกับวัตถุ

ชนิดข้อมูล BLOB

หากคุณต้องการบันทึกวัตถุบางอย่างลงในฐานข้อมูล วิธีที่ง่ายที่สุดในการดำเนินการนี้คือการใช้ประเภท SQL BLOB JDBC มีคู่หูที่เรียกว่า Blob

BLOB ย่อมาจากBinary L arge Object ใช้สำหรับเก็บอาร์เรย์ของไบต์ ประเภท Blob ใน JDBC เป็นอินเทอร์เฟซและคุณสามารถใส่ (และรับ) ข้อมูลได้สองวิธี:

  • การใช้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 Object ลงในฐานข้อมูล

เราได้เรียนรู้วิธีบันทึกไบนารีออบเจกต์ลงในฐานข้อมูล: อาร์เรย์ไบต์ สตรีมไบต์ และอื่นๆ แล้ววัตถุ 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 หรือการอ้างอิงไปยังวัตถุอื่นๆ ที่เราต้องการจัดเก็บไว้ในฐานข้อมูล

ความคิดเห็น
  • เป็นที่นิยม
  • ใหม่
  • เก่า
คุณต้องลงชื่อเข้าใช้เพื่อแสดงความคิดเห็น
หน้านี้ยังไม่มีความคิดเห็นใด ๆ