首页 | 联系我们 | 叶凡网络官方QQ群:323842844
游客,欢迎您! 请登录 免费注册 忘记密码
您所在的位置:首页 > 开发语言 > Java开发 > 正文

关于JdbcTemplate的用法

作者:cocomyyz 来源: 日期:2013-08-04 23:30:34 人气:111 加入收藏 评论:0 标签:java

表account字段:id,userName,password

Account.java

package com.brj.test;

public class Account {
private String userName;
private String password;

public String getUserName() {
  return userName;
}

public void setUserName(String userName) {
  this.userName = userName;
}

public String getPassword() {
  return password;
}

public void setPassword(String password) {
  this.password = password;
}

}


AccountDAO.java

package com.brj.test;

import javax.sql.DataSource;

import org.springframework.jdbc.core.JdbcTemplate;

public class AccountDAO {
private DataSource ds;

public void setDs(DataSource ds) {
  this.ds = ds;
}

public void saveAccount(Account account) {
  String sql = "insert into account(userName, password) values('"+account.getUserName()+"','"+account.getPassword()+"')";
  JdbcTemplate jt = new JdbcTemplate(ds);
  jt.execute(sql);
}

}


Test.java

package com.brj.test;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;

public class Test {

public static void main(String agrs[]){
  Account account = new Account();
  account.setUserName("loveyang");
  account.setPassword("loveyangtoo");
 
  ClassPathResource resource = new ClassPathResource("applicationContext.xml");
  BeanFactory factory = new XmlBeanFactory(resource);
 
  AccountDAO accountDAO = (AccountDAO)factory.getBean("accountDAO");
  accountDAO.saveAccount(account);
  System.out.println("Save Account successfully.");
}

}


applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<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.0.xsd">
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
  <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
  <property name="url" value="jdbc:mysql://localhost:3306/testdb"></property>
  <property name="username" value="root"></property>
  <property name="password" value="pass"></property>
</bean>

<bean id="accountDAO" class="com.brj.test.AccountDAO">
  <property name="ds" ref="dataSource"></property>
</bean>

</beans>


本文网址:http://www.mingyangnet.com/html/java/156.html
读完这篇文章后,您心情如何?
  • 0
  • 0
  • 0
  • 0
  • 0
  • 0
  • 0
  • 0
更多>>网友评论
发表评论
编辑推荐
  • 没有资料