SpringJDBC解析1-使用示例

JDBC(Java Data Base Connectivity,Java数据库连接)是一种用于执行SQL语句的JavaAPI,可以为多种关系数据库提供统一访问,它由一组用Java语言编写的类和接口组成。JDBC为数据库开发人员提供了一个标准的API,据此可以构建更高级的工具和接口,使数据库开发人员能够用纯JavaAPI编写数据库应用程序,并且可跨平台运行,并且不受数据库供应商的限制。
JDBC连接数据库的流程及其原理如下:

  1. 在开发环境中加载指定数据库的驱动程序。(Oracle用的包是oracle6-1.0.6.jar,MySQL用的是mysql-connector-java-5.1.18-bin.jar)。
  2. 在java程序中加载驱动程序。在java程序中,可以通过“Class.forName("com.mysql.jdbc.Driver")”加载MySQL的数据驱动程序。
  3. 创建数据库连接对象。通过DriverManager类创建数据库连接对象Connection.DriverManager类作用于Java程序和JDBC驱动程序之间,用于检查所加载的驱动程序是否可以建立连接,然后通过它的getConnection方法根据数据库的URL,用户名和密码,创建一个JDBC Connnection对象,例如:Connection connection=DriverManager.getConnection("连接数据库的URL","用户名","密码")。其中,URL=协议名+IP地址(域名)+端口+数据库名称;例如:Connection connectMySQL = DriverManager.getConnection("jdbc:mysql://localhost:3306/myuser","root","root");
  4. 创建Statement对象。Statement类的主要作用是用于执行静态SQL语句并返回它所生成结果的对象。通过Connection对象的createStatement()方法可以创建一个Statement对象。例如:Statement statement = connectMySQL.createStatement();
  5. 调用Statement对象的相关方法执行相应的SQL语句。通过excuteUpdate()方法来对数据更新,包括插入和删除操作,例如向staff表中插入一条数据的代码。statement.excuteUpdate("INSERT INTO staff(name,age,sex,address,depart,worklen,wage)"+"VALUES(‘Tom1’,'321','M','china','Personnel','3','3000')");通过调用Statement对象的executeQuery()方法进行数据的查询,而查询结果会得到ResultSet对象,ResultSet表示执行查询数据库后返回的数据的集合,ResultSet对象具有可以指向当前数据行的指针。通过该对象的next()方法,使得指针指向下一行,然后将 数据以列号或者字段名取出。如果当next()方法返回null,则表示下一行中没有数据存在。使用示例代码如下:ResultSet resultSet = statement.executeQuery("select * from staff");
  6. 关闭数据库连接。使用完数据库或者不需要访问数据库时,通过Connection的close()方法及时关闭连接。

SpringJDBC使用示例

创建数据库表(person)

CREATE TABLE 'user' (
    'id' int(11) NOT NULL auto_increment,
    'name' varchar(255) default NULL,
    'age' int(11) default NULL,
    'sex' varchar(255) default NULL,
    PRIMARY KEY ('id')
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

创建数据库表对应的po类

public class Person {  
    private String id;  
    private String name;  
    private String sex;  
    private int age;   
    //省略set get方法  
}  

创建表与实体之间的映射

public class PersonRowMapper implements RowMapper<Person>{  
    @Override  
    public Person mapRow(ResultSet rs, int rowNum) throws SQLException {  
        Person person=new Person();  
        person.setAge(rs.getInt("age"));  
        person.setName(rs.getString("name"));  
        person.setId(rs.getString("id"));  
        person.setSex(rs.getString("sex"));  
        return person;  
    }  
}  

创建数据库操作接口

public interface PersonService {  
    public void save(Person person);  
    public List<Person> getPersons();  
}  
public class PersonServiceImpl implements PersonService {  
    private JdbcTemplate jdbcTemplate;  
    public void setJdbcTemplate(DataSource dataSource) {  
        this.jdbcTemplate = new JdbcTemplate(dataSource);  
    }  
    public void save(Person p) {  
        jdbcTemplate.update("insert in to person(person_id,name,age,sex,come_from) values(?,?,?,?,?)",   
                new Object[]{p.getId(),p.getName(),p.getAge(),p.getSex()},   
                new int[]{Types.VARCHAR,Types.VARCHAR,Types.INTEGER,Types.VARCHAR});  
    }  
    public List<Person> getPersons(){  
        List<Person> list=jdbcTemplate.query("select * from person", new PersonRowMapper());  
        return list;  
    }  
}  

创建spring配置文件

<?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-3.0.xsd"> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/test"/> <property name="username" value="root"/> <property name="password" value="123456"/> <!-- 连接池启动时候的初始连接数 --> <property name="initialSize" value="10"/> <!-- 最小空闲值 --> <property name="minIdle" value="5"/> <!-- 最大空闲值 --> <property name="maxIdle" value="20"/> <property name="maxWait" value="2000"/> <!-- 连接池最大值 --> <property name="maxActive" value="50"/> <property name="logAbandoned" value="true"/> <property name="removeAbandoned" value="true"/> <property name="removeAbandonedTimeout" value="180"/> </bean> <!-- 配置业务bean --> <bean id="personService" class="***.PersonServiceImpl"> <!-- 向dataSource注入数据源 --> <property name="jdbcTemplate" ref="dataSource"/> </bean> </beans>

测试类

public class JdbcTest {  
    public static void main(String[] args) {  
        ApplicationContext context=new ClassPathXmlApplicationContext("classpath:bean.xml");  
        PersonService service=(PersonService) context.getBean("personService");  
        System.out.println(service.getPersons().size());  
    }  
}  
原文地址:https://www.cnblogs.com/wade-luffy/p/6079927.html