表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>