曾经测试过的jdbcTemplate例子源代码
JdbcTemplate的具体使用类:
import org.springframework.jdbc.core.JdbcTemplate;
public class UserDao {
JdbcTemplate template;
public JdbcTemplate getTemplate() {
return template;
}
public void setTemplate(JdbcTemplate template) {
this.template = template;
}
//利用jdbc的插入方法和更新方法都是update
public int insert(String name,int money){
int row=0;
String sql="INSERT INTO mybank VALUES(DEFAULT,?,?)";
Object[] args=new Object[]{name,money};
row=template.update(sql, args);
return row;
}
public int update(int userid,String name,int money){
int row=0;
String sql="UPDATE mybank SET username=?,money=? WHERE userid=?";
Object[] args=new Object[]{name,money,userid};
row=template.update(sql, args);
return row;
}
}
主测试方法:
import org.springframework.context.ApplicationContext;
importorg.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String[] args) {
ApplicationContext act=new ClassPathXmlApplicationContext("spring.xml");
UserDao dao=(UserDao) act.getBean("userDao");
int row=dao.insert("倚天剑",333);
System.out.println(row);
}
}
完整的配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<-beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<-bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/myjdbctest"></property>
<property name="user" value="root"></property>
<property name="password" value="rootroot"></property>
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
<bean id="userDao" class="com.defu.ss.UserDao" p:template-ref="jdbcTemplate"></bean>
</beans>