Spring:JDBC模板

「爱情、让人受尽委屈。」 2022-05-29 03:36 242阅读 0赞

我们通过几个实例来演示下JDBC模板。

创建Student类(id,name,age)和相应的数据库表。

创建接口:

public interface ISomeService {

void saveStudent(Student student);

void removeStudentById(int id);

void modifyStudent(Student student);

String findStudentNameById(int id);

List findAllStduetnName();

Student findStudentById(int id);

List findAllStudents();

}

Spring:JDBC模板

ISomeService实现类:SomeService

创建接口及其对应的实现类:

public interface ISomeDao {

void inserStudent(Student student);

void deleteStudentById(int id);

void updateStudent(Student student);

String selectStudentNameById(int id);

List selectAllStduetnName();

Student selectStudentById(int id);

List selectAllStudents();

}

在dao实现类里写sql语句如下:


一、插入数据:

Spring:JDBC模板


二、通过id删除数据:

Spring:JDBC模板


三、更新数据:

Spring:JDBC模板


四、通过id查询学生信息:

Spring:JDBC模板


五、查询所有信息包装成list类型:

Spring:JDBC模板


六、对自定义对象查询:

Spring:JDBC模板

我们这里要想将数据包装成student类型,必须创建个类,让这个类实现RowMapper接口,如图:

Spring:JDBC模板


七、使用DBCP数据源:需要导入DBCP的jar包和所依赖的pool包

Spring:JDBC模板


八、使用C3P0数据源:

需要导入相应的包

Spring:JDBC模板


九、DB连接四要素从属性文件中读取:

首先创建一个jdbc.propertis文件,里面放上:

jdbc.driver=com.mysql.jdbc.Driver

jdbc.url=jdbc:mysql:///student

jdbc.username=root

jdbc.password=111

Spring:JDBC模板

当然,注册方式还有另一种:

Spring:JDBC模板

这种方式虽然简单,但是需要添加context约束。


Spring:JDBC模板

测试类

发表评论

表情:
评论列表 (有 0 条评论,242人围观)

还没有评论,来说两句吧...

相关阅读

    相关 SpringJDBC源码解析

    注意,读完本篇文章需要很长很长时间 传统JDBC 相信大家对传统的jdbc已经很熟悉了,无非就是下面这个流程 <table> <tbody> <tr...