將對象保存到數據庫

開放

JDBC 數據類型的完整列表

除了您知道的數據類型之外,JDBC 還允許您使用 DBMS 的許多本機數據類型。下面我將列出類型和獲取它們的函數:

類型 方法
大批 獲取數組()
AsciiStream 獲取 AsciiStream()
大數 getBigDecimal()
二進制流 getBinaryStream()
斑點 獲取Blob()
布爾值 獲取布爾值()
斑點 獲取Blob()
布爾值 獲取布爾值()
字節 獲取字節()
字節 獲取字節()
字符流 獲取字符流()
團塊 得到Clob()
日期 獲取日期()
雙倍的 getDouble()
漂浮 得到浮點數()
整數 獲取整數()
長的 獲取長()
N字符流 getNCharacterStream() 函數
目的 獲取對象()
參考 獲取引用()
行號 獲取行號()
短的 getShort()
SQLXML 獲取SQLXML()
細繩 獲取字符串()
時間 獲取時間()
時間戳 獲取時間戳()
UnicodeStream 獲取UnicodeStream()
網址 獲取網址()

我們已經考慮過原始類型。現在讓我們嘗試使用對象。

BLOB 數據類型

如果你想將一些對象保存到數據庫中,那麼最簡單的方法就是使用 SQL BLOB 類型。JDBC 有它的對應物 Blob。

BLOB代表二進制對象_ _ 它用於存儲字節數組。JDBC 中的 Blob 類型是一個接口,您可以通過兩種方式將數據放入(和接收)其中:

  • 使用輸入流
  • 使用字節數組

示例:第 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
}

現在讓我們編寫將Employee類的對象添加到基類的代碼:

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 或對我們也想存儲在數據庫中的其他對象的引用),這將特別有用。

留言
  • 受歡迎
你必須登入才能留言
此頁面尚無留言