它是使用JDBC(Java Database Connectivity)来与数据库进行交互的。JDBC是Java的一个标准API,用于执行SQL语句、连接和操作数据库。
在该代码中,首先使用javax.sql.DataSource获取数据库连接,然后通过PreparedStatment对象执行SQL语句,最后通过executeUpdate()方法执行更新操作。JDBC提供了一系列的接口和类来实现数据库连接、查询和更新操作,而MyBatis是一个持久层框架,它建立在JDBC之上,提供了更便捷的ORM(对象-关系映射)功能,可以避免手动编写JDBC的代码,提高开发效率。
核心代码
package com.example.demo_zcgc.dao;
import com.example.demo_zcgc.entity.Person;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import javax.sql.DataSource;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
@Repository
public class PersonDaoImpl implements PersonDao {
@Autowired
DataSource dataSource;
public List<Person> selectAllPerson() {
List<Person> personList = new ArrayList<>();
// 连接数据库,执行查询操作
try (Connection conn = dataSource.getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM person"))
{
while (rs.next()) {
String name = rs.getString("name");
int age = rs.getInt("age");
String sex = rs.getString("sex");
Long id = rs.getLong("id");
Person person = new Person(name, age, sex,id);
personList.add(person);
}
} catch (SQLException e) {
e.printStackTrace();
}
return personList;
}
@Override
public int addPerson(Person person) {
String sql = "INSERT INTO person (name, age, sex,id) VALUES (?, ?, ?,?)";
try (Connection conn = dataSource.getConnection();
PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setString(1, person.getName());
pstmt.setInt(2, person.getAge());
pstmt.setString(3, person.getSex());
pstmt.setLong(4, person.getId());
return pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
return 0;
}
@Override
public int delPerson(Person person) {
String sql = "DELETE FROM person WHERE id=?";
System.out.format("dao name=%s,age=%d,sex=%s\n",person.getName(),person.getAge(),person.getSex());
try (Connection conn = dataSource.getConnection();
PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setLong(1, person.getId());
return pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
return 0;
}
@Override
public int updPerson(Person person) {
String sql = "UPDATE person SET name=?, age=?, sex=? WHERE id=?";
try (Connection conn = dataSource.getConnection();
PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setString(1, person.getName());
pstmt.setInt(2, person.getAge());
pstmt.setString(3, person.getSex());
pstmt.setLong(4, person.getId());
return pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
return 0;
}
@Override
public int delAllPerson() {
String sql = "DELETE FROM person";
try (Connection conn = dataSource.getConnection();
PreparedStatement pstmt = conn.prepareStatement(sql)) {
return pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
return 0;
}
}