当前位置:Gxlcms > 数据库问题 > (二)Spring框架之JDBC的基本使用

(二)Spring框架之JDBC的基本使用

时间:2021-07-01 10:21:17 帮助过:14人阅读

jdbc; import java.lang.Thread.State; import java.sql.Connection; import java.sql.Statement; import javax.sql.DataSource; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * 本类中的数据源dataSource成员属性是通过IOC方式注入, * @author 半颗柠檬、 * */ public class Test_2 { private DataSource dataSource; public void setDataSource(DataSource dataSource) { this.dataSource = dataSource; } public void addUser() throws Exception{ String sql="insert into user value(‘111‘,15,‘男‘)"; System.out.println(this.dataSource); Connection conn=null; Statement stat=null; try { conn=this.dataSource.getConnection(); System.out.println("conn="+conn); stat=conn.createStatement(); stat.executeUpdate(sql); } catch (Exception e) { e.printStackTrace(); }finally{ // conn.close(); // stat.close(); } } public static void main(String[] args) throws Exception { /* * 这里不能用Test_2 test_2=new Test_2() 这种方法来获得Test_2对象,否则spring.xml里把DataSource注入到Test_2的成员变量dataSource将无效。 */ ApplicationContext context=new ClassPathXmlApplicationContext("spring.xml"); Test_2 test_2=(Test_2)context.getBean("test_2"); test_2.addUser(); } }

  spring.xml

<bean id="dateSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <!-- 推荐使用配置文件的方法来设置数据源的参数-->
        
        <constructor-arg index="0" name="driverClassName" value="com.mysql.jdbc.Driver"></constructor-arg>
        <!-- xml文件中不能直接用&号,要用"&amp;"取代,否则报错,如下 -->
        <constructor-arg index="1" value="jdbc:mysql://127.0.0.1:3306/user?useUnicode=true&amp;characterEncoding=UTF-8"></constructor-arg>
        <constructor-arg index="2" name="username" value="root"></constructor-arg>
        <constructor-arg index="3" name="password" value=""></constructor-arg>
    </bean>
    
    <!-- test_2类中需要的配置 -->
    <bean id="test_2" class="jdbc.Test_2">
        <property name="dataSource"  ref="dateSource"></property>
    </bean>
    <!-- end -->
  • 其中org.springframework.jdbc.datasource.DriverManagerDataSource 类是用来设置数据源的。

结果:

技术分享

 



 

  •   案例二: 使用JdbcTemplate模版来使用jdbc。
    • JdbcTemplate对数据库的操作在jdbc上面做了深层次的封装。

 

  Test_3.java

package jdbc;

import javax.sql.DataSource;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;

/**
 * Spring对数据库的操作在jdbc上面做了深层次的封装,
 * 使用spring的注入功能,可以把DataSource注册到JdbcTemplate之中。
 * @author Administrator
 *
 */
public class Test_3 {
private DataSource dataSouce; public void setDataSouce(DataSource dataSouce) { this.dataSouce = dataSouce; } public void addUser(){ String sql="insert into user value(‘222‘,15,‘男‘)"; JdbcTemplate jdbcTemplate=new JdbcTemplate(this.dataSouce); jdbcTemplate.execute(sql); } public static void main(String[] args) { ApplicationContext context=new ClassPathXmlApplicationContext("spring.xml"); Test_3 test_3=(Test_3)context.getBean("test_3"); test_3.addUser(); } }

  spring.xml

<bean id="dateSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <!-- 推荐使用配置文件的方法来设置数据源的参数-->
        
        <constructor-arg index="0" name="driverClassName" value="com.mysql.jdbc.Driver"></constructor-arg>
        <!-- xml文件中不能直接用&号,要用"&amp;"取代,否则报错,如下 -->
        <constructor-arg index="1" value="jdbc:mysql://127.0.0.1:3306/user?useUnicode=true&amp;characterEncoding=UTF-8"></constructor-arg>
        <constructor-arg index="2" name="username" value="root"></constructor-arg>
        <constructor-arg index="3" name="password" value=""></constructor-arg>
    </bean>

    
    <!-- test_3类中需要的配置 -->
    <bean id="test_3" class="jdbc.Test_3">
        <property name="dataSouce" ref="dateSource"></property>
    </bean>
    <!-- end-->
    

结果:

技术分享



  •   案例三:   将JdbcTemplate作为成员属性,直接在类中使用。

 Test_4.java

package jdbc;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;

/**
 * pring.xml中将jdbctemplate模版注入到本类中,
 * jdbctemplate模版中又需要注入一个数据源的对象。
 * @author Administrator
 *
 */
public class Test_4 {
        
    private JdbcTemplate jdbctemplate;

    public void setJdbctemplate(JdbcTemplate jdbctemplate) {
        this.jdbctemplate = jdbctemplate;
    }
      
    public void addUser(){
        String sql="insert into user value(‘333‘,15,‘男‘)";
        this.jdbctemplate.execute(sql);
    }
    
        public static void main(String[] args) {
            
            ApplicationContext context=new ClassPathXmlApplicationContext("spring.xml");
            Test_4 test_4=(Test_4)context.getBean("test_4");
            test_4.addUser();
            
        }
            
}

  spring.xml

    <bean id="dateSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <!-- 推荐使用配置文件的方法来设置数据源的参数-->
        
        <constructor-arg index="0" name="driverClassName" value="com.mysql.jdbc.Driver"></constructor-arg>
        <!-- xml文件中不能直接用&号,要用"&amp;"取代,否则报错,如下 -->
        <constructor-arg index="1" value="jdbc:mysql://127.0.0.1:3306/user?useUnicode=true&amp;characterEncoding=UTF-8"></constructor-arg>
        <constructor-arg index="2" name="username" value="root"></constructor-arg>
        <constructor-arg index="3" name="password" value=""></constructor-arg>
    </bean>

        <!-- test_4类中需要的配置 -->
    <bean id="jdbctemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dateSource"></property>
    </bean>
    
    <bean id="test_4" class="jdbc.Test_4">
        <property name="jdbctemplate" ref="jdbctemplate"></property>
    </bean>
    <!-- end -->            

结果:

技术分享



  案例四: 使用JdbcDaoSupport包来使用spring JDBC

  • Test_5.java
package jdbc;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

/**
 * 使用JdbcDaoSupport包来使用spring JDBC
 * JdbcDaoSupport是JDBC数据访问对象的超类。它与特定的数据源相关联。这个类最重要的功能就是使子类可以使用JdbcTemplate对象。 
 * @author 半颗柠檬、
 *
 */
public class Test_5  extends JdbcDaoSupport{
    
    private void addUser(){
        String sql="insert into user value(‘555‘,15,‘男‘)";
        this.getJdbcTemplate().execute(sql);
    }
    
    
    public static void main(String[] args) {
        ApplicationContext context=new ClassPathXmlApplicationContext("spring.xml");

        Test_5 test_5=(Test_5)context.getBean("test_5");
        test_5.addUser();
    }

}
  • spring.xml
     <bean id="dateSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <!-- 推荐使用配置文件的方法来设置数据源的参数-->
        
        <constructor-arg index="0" name="driverClassName" value="com.mysql.jdbc.Driver"></constructor-arg>
        <!-- xml文件中不能直接用&号,要用"&amp;"取代,否则报错,如下 -->
        <constructor-arg index="1" value="jdbc:mysql://127.0.0.1:3306/user?useUnicode=true&amp;characterEncoding=UTF-8"></constructor-arg>
        <constructor-arg index="2" name="username" value="root"></constructor-arg>
        <constructor-arg index="3" name="password" value=""></constructor-arg>
    </bean>

       <!-- test_5类中需要的配置 -->
    <bean id="jdbctemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dateSource"></property>
    </bean>

    <!-- test_5类中需要的配置 -->
    <bean id="test_5" class="jdbc.Test_5" >
        <property name="jdbcTemplate" ref="jdbctemplate">
        </property>
    </bean>    

结果:

技术分享



  •  案例五: spring jdbc 进行DML(DML 数据操作语言 (insert/update/delete 等语句))

 Test_DML.java

 

package jdbc;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

/**
 * DML 数据操作语言 (insert/update/delete 等语句)。
 * 
 * @author 半颗柠檬、
 *
 */
public class Test_DML extends JdbcDaoSupport{
    /**
     * insert语句
     */
    private void insert(){
        String sql="insert into  user values(‘666‘,15,‘女‘)";
        this.getJdbcTemplate().execute(sql);
    }
    
    /**
     *更新语句 
     */
    private void update() {
        String sql="update  user set sex=‘男‘ where userName=‘111‘";
        this.getJdbcTemplate().execute(sql);
    }
    
    /**
     * 删除语句
     */
    private void delete() {
    
        String sql="delete from user where userName=‘111‘";
        this.getJdbcTemplate().execute(sql);
        
    }

    public static void main(String[] args) {
        
        ApplicationContext context=new ClassPathXmlApplicationContext("spring.xml");
        Test_DML test_DML=(Test_DML) context.getBean("test_DML");
        
        test_DML.insert();
    //    test_DML.update();
    //    test_DML.delete();
        
    }
}

  spring.xml

    <bean id="dateSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <!-- 推荐使用配置文件的方法来设置数据源的参数-->
        
        <constructor-arg index="0" name="driverClassName" value="com.mysql.jdbc.Driver"></constructor-arg>
        <!-- xml文件中不能直接用&号,要用"&amp;"取代,否则报错,如下 -->
        <constructor-arg index="1" value="jdbc:mysql://127.0.0.1:3306/user?useUnicode=true&amp;characterEncoding=UTF-8"></constructor-arg>
        <constructor-arg index="2" name="username" value="root"></constructor-arg>
        <constructor-arg index="3" name="password" value=""></constructor-arg>
    </bean>
    
    
    <bean id="jdbctemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dateSource"></property>
    </bean>
    
  
    <!-- test_DML类中需要的配置 -->
    <bean id="test_DML" class="jdbc.Test_DML" >
        <property name="jdbcTemplate" ref="jdbctemplate">
        </property>
    </bean>
    <!-- end -->

结果:

技术分享



  • 案例六: spring jdbc 进行DDL(DDL 数据定义语言(create/drop/alter))

 Test_DDL.java

 

package jdbc;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
/**
 * DDL 数据定义语言(create/drop/alter)
 * @author 半颗柠檬、
 *
 */
public class Test_DDL  extends JdbcDaoSupport{
    /*
     *create语句
     */
    private void create() {
        String sql="create table abc (name int)";
        this.getJdbcTemplate().execute(sql);

    }
    /*
     * drop语句
     */
    private void drop() {
        String sql="drop table abc";
        this.getJdbcTemplate().execute(sql);

    }
    /*
     * alter语句
     */
    private void alter() {
        String sql="alter table abc add birthday date";
        this.getJdbcTemplate().execute(sql);
    }
    
    public static void main(String[] args) {
        
        ApplicationContext context=new ClassPathXmlApplicationContext("spring.xml");
        Test_DDL test_DDL=(Test_DDL)context.getBean("test_DDL");
        test_DDL.create();  
    //    test_DDL.drop();
    //    test_DDL.alter();
        
    }
}

  spring.xml

    
<bean id="dateSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <!-- 推荐使用配置文件的方法来设置数据源的参数-->
        
        <constructor-arg index="0" name="driverClassName" value="com.mysql.jdbc.Driver"></constructor-arg>
        <!-- xml文件中不能直接用&号,要用"&amp;"取代,否则报错,如下 -->
        <constructor-arg index="1" value="jdbc:mysql://127.0.0.1:3306/user?useUnicode=true&amp;characterEncoding=UTF-8"></constructor-arg>
        <constructor-arg index="2" name="username" value="root"></constructor-arg>
        <constructor-arg index="3" name="password" value=""></constructor-arg>
    </bean>

    <bean id="jdbctemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dateSource"></property>
    </bean>

        <!-- test_DDL类中需要的配置 -->
        <bean id="test_DDL" class="jdbc.Test_DDL">
            <property name="jdbcTemplate" ref="jdbctemplate"></property>
        </bean>
    <!-- end -->    

结果:

技术分享



  • 案例七:spring JDBC 使用预处理语句

 Test_prepared.java

 

package jdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.PreparedStatementCallback;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.core.PreparedStatementSetter;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

/**
 * spring JDBC 的预编译语句
 *  本类中有三种方式来处理预编译语句
 * @author 半颗柠檬、
 *
 */

public class Test_prepared extends JdbcDaoSupport {

    private void prepared_1() {

        String sql = "update user set age=?,sex=? where userName=?";

        this.getJdbcTemplate().update(sql, new PreparedStatementSetter() {

            public void setValues(PreparedStatement ps) throws SQLException {
                ps.setInt(1, 105);
                ps.setString(2, "女");
                ps.setString(3, "张三");

            }

        });

    }

    private void prepared_2() {
        final String sql = "update user set age=?,sex=? where userName=?";
        this.getJdbcTemplate().update(new PreparedStatementCreator() {

            public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
                PreparedStatement pstat = con.prepareStatement(sql);

                pstat.setInt(1, 1);
                pstat.setString(2, "NONE");
                pstat.setString(3, "张三");

                return pstat;
            }
        });

    }

    private void prepared_3() {
        String sql = "update user set age=?,sex=? where userName=?";
        Object[] obj={500,"女","张三"};
        this.getJdbcTemplate().update(sql,obj);

    }

    public static void main(String[] args) {

        ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
        Test_prepared test_prepared = (Test_prepared) context.getBean("test_prepared");
    //    test_prepared.prepared_1();
    //    test_prepared.prepared_2();
        test_prepared.prepared_3();
    
    }
}

spring.xml

<bean id="dateSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <!-- 推荐使用配置文件的方法来设置数据源的参数-->
        
        <constructor-arg index="0" name="driverClassName" value="com.mysql.jdbc.Driver"></constructor-arg>
        <!-- xml文件中不能直接用&号,要用"&amp;"取代,否则报错,如下 -->
        <constructor-arg index="1" value="jdbc:mysql://127.0.0.1:3306/user?useUnicode=true&amp;characterEncoding=UTF-8"></constructor-arg>
        <constructor-arg index="2" name="username" value="root"></constructor-arg>
        <constructor-arg index="3" name="password" value=""></constructor-arg>
    </bean>

    <bean id="jdbctemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dateSource"></property>
    </bean>

  <!-- test_prepared类中需要的配置 -->
        <bean id="test_prepared" class="jdbc.Test_prepared">
            <property name="jdbcTemplate" ref="jdbctemplate"></property>
        </bean>
    <!-- end -->

结果:

技术分享



  • 案例八:spring JDBC 的几种查询操作,并返回各种类型的结果集。

 Test_Query.java

package jdbc;

import java.util.List;
import java.util.Map;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
/**
 * spring JDBC 的几种查询操作,并返回各种类型的结果集
 * @author 半颗柠檬、
 *
 */
public class Test_Query extends JdbcDaoSupport{

    /*
     * 把查询结果为多行数据封装为一个List,List中每个对象为一个Map,Map中存放着数据库中每行的数据(以列名=值的形式)
     */
    private void queryForList() {
        String sql="select * from user";
    List<Map<String,Object>> listMap=    this.getJdbcTemplate().queryForList(sql);

        for(Map<String, Object> map:listMap){
            
            System.out.println(map);
        }

    }
    
    /*
     * 把查询结果为单行数据封装为一个Map。
     */
    private void queryForMap() {
     String sql="select * from user where userName=‘李四‘";
     
     Map<String,Object> map=this.getJdbcTemplate().queryForMap(sql);
     
     System.out.println(map);

    }
    
    /**
     * 把查询结果为单行(多行)数据封装为自定义Object类型
     */
    private void queryForObject() {
        /**
         * 查询某个表中共有多少条数据,queryForObject(sql, requiredType) 中的requiredType只能为基本类型或者String类型(也不能是这些类型的数组),
         * 否则报错,查询的结果也只能是查询某个表中某一列的数据且只能是一条数据,
         */
        String sql="select count(1) from user";
        Long rsCount=    this.getJdbcTemplate().queryForObject(sql, Long.class);
        
        System.out.println(rsCount);
    
    }
    
    public static void main(String[] args) {
        ApplicationContext context=new ClassPathXmlApplicationContext("spring.xml");
    
        Test_Query test_Query=(Test_Query) context.getBean("test_Query");

    //    test_Query.queryForList();
    
    //    test_Query.queryForMap();
        test_Query.queryForObject();
    }
}

spring.xml

<bean id="dateSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <!-- 推荐使用配置文件的方法来设置数据源的参数-->
        
        <constructor-arg index="0" name="driverClassName" value="com.mysql.jdbc.Driver"></constructor-arg>
        <!-- xml文件中不能直接用&号,要用"&amp;"取代,否则报错,如下 -->
        <constructor-arg index="1" value="jdbc:mysql://127.0.0.1:3306/user?useUnicode=true&amp;characterEncoding=UTF-8"></constructor-arg>
        <constructor-arg index="2" name="username" value="root"></constructor-arg>
        <constructor-arg index="3" name="password" value=""></constructor-arg>
    </bean>

    <bean id="jdbctemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dateSource"
                        
                    

人气教程排行