Spring:JDBC模板
我们通过几个实例来演示下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
Student findStudentById(int id);
List
}
ISomeService实现类:SomeService
创建接口及其对应的实现类:
public interface ISomeDao {
void inserStudent(Student student);
void deleteStudentById(int id);
void updateStudent(Student student);
String selectStudentNameById(int id);
List
Student selectStudentById(int id);
List
}
在dao实现类里写sql语句如下:
一、插入数据:
二、通过id删除数据:
三、更新数据:
四、通过id查询学生信息:
五、查询所有信息包装成list类型:
六、对自定义对象查询:
我们这里要想将数据包装成student类型,必须创建个类,让这个类实现RowMapper接口,如图:
七、使用DBCP数据源:需要导入DBCP的jar包和所依赖的pool包
八、使用C3P0数据源:
需要导入相应的包
九、DB连接四要素从属性文件中读取:
首先创建一个jdbc.propertis文件,里面放上:
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc///student
jdbc.username=root
jdbc.password=111
当然,注册方式还有另一种:
这种方式虽然简单,但是需要添加context约束。
测试类
还没有评论,来说两句吧...