本文介绍使用最原始的JDBC方式。 1. 建表,表结构如下; 2.配置数据源; <?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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.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/xwh" /> <property name="username" value="root" /> <property name="password" value="root" /> </bean> <bean id="student" class="com.chapter5.Student"> <property name="id" value="4"/> <property name="name" value="jack"/> </bean> <bean id="studentDao" class="com.chapter5.StudentDao"> <property name="dataSource" ref="datasource"/> </bean> </beans> 3.新建相应的POJO类 package com.chapter5; public class Student { int id; String name; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } 4.新建DAO package com.chapter5; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import javax.sql.DataSource; public class StudentDao { DataSource dataSource; private static final String student_insert = "insert into student values(?,?)"; /** * 使用Spring的注入方式 * @param dataSource */ public void setDataSource(DataSource dataSource) { this.dataSource = dataSource; } /** * 客套话太多 * @param student */ public void saveData(Student student) { Connection conn = null; PreparedStatement stmt = null; try { conn = dataSource.getConnection(); stmt = conn.prepareStatement(student_insert); stmt.setInt(1, student.getId()); stmt.setString(2, student.getName()); stmt.execute(); } catch(SQLException e) { e.printStackTrace(); } finally { try { if(stmt != null) { stmt.close(); } if(conn != null) { conn.close(); } System.out.println("成功入库!"); } catch(SQLException e) { e.printStackTrace(); } } } } 5.测试 package com.chapter5; import org.springframework.beans.factory.BeanFactory; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Test { public static void main(String[] args) { BeanFactory factory = new ClassPathXmlApplicationContext("springdao.xml"); Student student = (Student) factory.getBean("student"); StudentDao studentDao = (StudentDao) factory.getBean("studentDao"); studentDao.saveData(student); } }