private datasource datasource;
public void setdatasource(datasource datasource) {
this.datasource = datasource;
}
public void insert(customer customer){
string sql = "insert into customer " +
"(cust_id, name, age) values (?, ?, ?)";
connection conn = null;
try {
conn = datasource.getconnection();
preparedstatement ps = conn.preparestatement(sql);
ps.setint(1, customer.getcustid());
ps.setstring(2, customer.getname());
ps.setint(3, customer.getage());
ps.executeupdate();
ps.close();
} catch (sqlexception e) {
throw new runtimeexception(e);
} finally {
if (conn != null) {
try {
conn.close();
} catch (sqlexception e) {}
}
}
}
private datasource datasource;
private jdbctemplate jdbctemplate;
public void setdatasource(datasource datasource) {
this.datasource = datasource;
}
public void insert(customer customer){
string sql = "insert into customer " +
"(cust_id, name, age) values (?, ?, ?)";
jdbctemplate = new jdbctemplate(datasource);
jdbctemplate.update(sql, new object[] { customer.getcustid(),
customer.getname(),customer.getage()
});
}
通过扩展 jdbcdaosupport,设置数据源,并且 jdbctemplate 在你的类中不再是必需的,只需要正确的数据源注入jdbccustomerdao。可以使用 getjdbctemplate()方法得到 jdbctemplate。
public class jdbccustomerdao extends jdbcdaosupport implements customerdao
{
//no need to set datasource here
public void insert(customer customer){
string sql = "insert into customer " +
"(cust_id, name, age) values (?, ?, ?)";
getjdbctemplate().update(sql, new object[] { customer.getcustid(),
customer.getname(),customer.getage()
});
}
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"
xsi:schemalocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="datasource"
class="org.springframework.jdbc.datasource.drivermanagerdatasource">
<property name="driverclassname" value="com.mysql.jdbc.driver" />
<property name="url" value="jdbc:mysql://localhost:3306/h3java" />
<property name="username" value="root" />
<property name="password" value="password" />
</bean>
</beans>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xsi:schemalocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <bean id="customerdao" class="com.h3.customer.dao.impl.jdbccustomerdao"> <property name="datasource" ref="datasource" /> </bean> </beans>