将对象保存到数据库

可用

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 或对我们也想存储在数据库中的其他对象的引用),这将特别有用。

评论
  • 受欢迎
你必须先登录才能发表评论
此页面还没有任何评论