JDBC学习笔记

本文档展示了如何使用Spring框架进行JDBC操作,包括数据库连接配置、工具类的编写、JDBC连接工具、数据的增删改查操作。同时,文章详细介绍了如何将这些功能整合到Spring中,利用Spring的事务管理进行数据操作,以及如何编写测试类验证功能。最后,提到了Spring的JdbcTemplate和事务控制的配置与使用。
摘要由CSDN通过智能技术生成

一、依赖及数据库连接参数配置

都是连的oracle,与mybatis学习笔记一样,jdbc只需增加ojdbc依赖。

二、获取文件路径工具类

class FileUtil {

    private String charset = "UTF-8";

    private URL getFileURL(String fileName) {
        ClassLoader loader = getClass().getClassLoader();
        return loader.getResource(fileName);
    }

    String getFilePath(String fileName) {
        URL url = getFileURL(fileName);
        try {
            return URLDecoder.decode(url.getPath(), charset);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }
}

三、读取配置文件工具类

public class PropertiesUtil {

    private static Properties propt = null;

    //读取配置文件,并将结果写入静态变量中,方便后续随时取用
    public static void setPropt() {
        //防止重复读配置文件
        if (propt == null) {
            FileUtil fileUrl = new FileUtil();
            //配置文件路径
            String path = fileUrl.getFilePath("db.properties");
            InputStreamReader is = null;
            try {
                //加字符集,考虑配置文件中有中文的情况
                is = new InputStreamReader(new FileInputStream(path),"GBK");
                propt = new Properties();
                propt.load(is);
            } catch (Exception e) {
//                throw new RuntimeException("加载配置文件失败!");
            } finally {
                IOUtils.closeQuietly(is);
            }
        }
    }

    public static Properties getPropt() {
        return propt;
    }
}

四、 JDBC连接工具类

public class MyJdbcUtil {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 获取连接
     */
    public Connection getConnection() {

        try {
            //读取配置文件
            PropertiesUtil.setPropt();
            //加载驱动
            Class.forName(PropertiesUtil.getPropt().getProperty("test_driver"));
            //获取连接
            Connection connection = DriverManager.getConnection(PropertiesUtil.getPropt().getProperty("test_url"),
                    PropertiesUtil.getPropt().getProperty("test_username"),
                    PropertiesUtil.getPropt().getProperty("test_password"));
            //开启事务控制
            connection.setAutoCommit(false);
            return connection;
        } catch (Exception ex) {
            logger.error("创建数据库连接失败", ex);
        }
        return null;
    }
}

五、数据的增、删、改、查

1、增、删、改

//通过对象传递入参,先用jdbc工具类建立连接,并开启事务控制
public int deleteAc01WebTest(Ac01WebTest ac01WebTest, Connection connection) {
	PreparedStatement statement = null;
    //增、删、改语句,?为占位符,用于接收条件入参,防止sql注入
	String sql = "delete ac01_web_test where aac001 = ? and aa013 = ?";
	try {
		statement = connection.prepareStatement(sql);
        //压入参数
		statement.setString(1, ac01WebTest.getAac001());
		statement.setString(2,"aaa");
        //执行语句
		int result = statement.executeUpdate();
        //返回结果,调用方通过返回结果,知道是否成功,进而决定继续还是回滚
		return result;
	} catch (Exception e) {
		e.printStackTrace();
		return error;//定义了一个error变量,错误就返回这个值
	} finally {
		if (statement != null) {
			try {
				statement.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
}

2、查

//将查询结果放入list中
public List<Ac01WebTest> queryAc01WebTest(Ac01WebTest ac01WebTest, Connection connection) {
	PreparedStatement statement = null;
	String sql = "select * from ac01_web_test where aac001 = ?";
	List<Ac01WebTest> ac01WebTests = new ArrayList<Ac01WebTest>();
	try {
		statement = connection.prepareStatement(sql);
		statement.setString(1, ac01WebTest.getAac001());
		//获取查询结果
		ResultSet resultSets = statement.executeQuery();
		//遍历结果
		while(resultSets.next()){
			//声明实例存放查询结果
			Ac01WebTest ac01WebTestResult = new Ac01WebTest();
			ac01WebTestResult.setAac001(resultSets.getString("aac001"));
			ac01WebTestResult.setAac002(resultSets.getString("aac002"));
			ac01WebTestResult.setAac003(resultSets.getString("aac003"));
			ac01WebTestResult.setAa013(resultSets.getString("aa013"));
			//考虑多条记录,放入list
			ac01WebTests.add(ac01WebTestResult);
		}
		return ac01WebTests;
	} catch (Exception e) {
		e.printStackTrace();
		return null;
	} finally {
		if (statement != null) {
			try {
				statement.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
}

六、编写测试类


public void testMyjdbcUtil() throws Exception {
    //声明jdbc工具类实例
	MyJdbcUtil myJdbcUtil = new MyJdbcUtil();
    //获取数据库连接
	Connection connection = myJdbcUtil.getConnection();

	//声明一个参数类(入参,将此对象内容压入相应sql语句占位的参数)
	Ac01WebTest ac01WebTest = new Ac01WebTest();
	ac01WebTest.setAac001("1");
	ac01WebTest.setAac002("1");
	ac01WebTest.setAac003("1");

    //声明数据库操作实现类实例
	Ac01WebTestDao ac01WebTestDao = new Ac01WebTestDaoImpl();

	//增
	result = ac01WebTestDao.insertAc01WebTest(ac01WebTest, connection);
    //如果处理结果代码为错误,事务回滚,并中断处理
	if (result == 0) {
		connection.rollback();
		return;
	}
	//删
	result = ac01WebTestDao.deleteAc01WebTest(ac01WebTest, connection);
	if (result == 0) {
		connection.rollback();
		return;
	}
	//查
	List<Ac01WebTest> ac01WebTests = ac01WebTestDao.queryAc01WebTest(ac01WebTest, connection);
	if (ac01WebTests != null) {
		//打印查询结果
		for (Ac01WebTest ac01WebTestResult : ac01WebTests) {
			System.out.println(ac01WebTestResult.toString());
		}
	} else {
		System.out.println("没有查询到记录");
	}
	//改
    //设置要修改的内容
	ac01WebTest.setAac003("2");
	result = ac01WebTestDao.updateAc01WebTest(ac01WebTest, connection);
	if (result == 0) {
		connection.rollback();
		return;
	}

	connection.close();
}

七、整合到spring

1、添加依赖

<dependency>
	<groupId>....org.springframework</groupId>
	<artifactId>spring-webmvc</artifactId>
	<version>5.2.4.RELEASE</version>
</dependency>
<!--没有这个依赖,事务控制时,插入aop切点就会报错-->
<!--Cannot resolve reference to bean 'pt1' while setting bean property 'pointcut'; 在设置bean属性'pointcut'时无法解析对bean'pt1'的引用-->
<!--Failed to instantiate [org.springframework.aop.aspectj.AspectJExpressionPointcut]: No default constructor found;-->
<!--未能实例化[org.springframework.aop.aspectj.AspectJExpressionPointcut]:找不到默认的构造函数;-->
<dependency>
	<groupId>org.aspectj</groupId>
	<artifactId>aspectjweaver</artifactId>
	<version>1.9.8</version>
</dependency>

<dependency>
	<groupId>.org.springframework</groupId>
	<artifactId>spring-jdbc</artifactId>
	<version>5.2.4.RELEASE</version>
</dependency>

<dependency>
	<groupId>com.oracle</groupId>
	<artifactId>ojdbc6</artifactId>
	<version>11.2.0.4</version>
</dependency>
<!--有spring-webmvc依赖,下面的依赖都可以不用再写-->
<!--<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-tx</artifactId>
	<version>5.0.2.RELEASE</version>
</dependency>
<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-aop</artifactId>
	<version>5.0.2.RELEASE</version>
</dependency>
<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-beans</artifactId>
	<version>5.2.1.RELEASE</version>
</dependency>
<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-core</artifactId>
	<version>5.2.1.RELEASE</version>
</dependency>
<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-context</artifactId>
	<version>5.2.1.RELEASE</version>
</dependency>
<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-expression</artifactId>
	<version>5.2.1.RELEASE</version>
</dependency>
<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-aspects</artifactId>
	<version>5.2.1.RELEASE</version>
</dependency>-->

2、改造数据库操作的dao类

//extends JdbcDaoSupport就可以不用增加jdbcTemplate属性了
public class Ac01WebTestDaoImpl extends JdbcDaoSupport implements Ac01WebTestDao {

    private Ac01WebTest ac01WebTest;
    public Ac01WebTest getAc01WebTest() { return ac01WebTest; }
    public void setAc01WebTest(Ac01WebTest ac01WebTest) {
        this.ac01WebTest = ac01WebTest;
    }

    /*增、删、改*/
    @Override
    public int insertAc01WebTest() {
        //sql语句
        String sql = "insert into ac01_web_test(aac001,aac002,aac003,aa013) values(?,?,?,?)";
        //参数传递
        Object[] obj = new Object[] { ac01WebTest.getAac001(), ac01WebTest.getAac002(),ac01WebTest.getAac003(),"admin" };
        int result = getJdbcTemplate().update(sql,obj);
        return result;
    }

    /*查*/
    @Override
    public List<Ac01WebTest> queryAc01WebTest() {
        String sql = "select * from ac01_web_test where aac001 = ? and aa013 = ?";
        // 创建一个新的BeanPropertyRowMapper对象
        RowMapper<Ac01WebTest> rowMapper = new BeanPropertyRowMapper<Ac01WebTest>(Ac01WebTest.class);
        Object[] obj = new Object[] { ac01WebTest.getAac001(),"admin" };
        //执行静态查询的sql,通过RowMapper返回结果
        return this.getJdbcTemplate().query(sql, obj, rowMapper);
    }
}

3、增加service层处理数据,事务控制也会放在这一层

public class Ac01WebTestServiceImpl implements Ac01WebTestService {
    @Autowired
    private Ac01WebTestDao ac01WebTestDao;
    private int result;

    public Ac01WebTestDao getAc01WebTestDao() {
        return ac01WebTestDao;
    }

    public void setAc01WebTestDao(Ac01WebTestDao ac01WebTestDao) {
        this.ac01WebTestDao = ac01WebTestDao;
    }

    @Override
    public int modefyAc01WebTest() {
        //声明一个参数类
        Ac01WebTest ac01WebTest = ac01WebTestDao.getAc01WebTest();
        ac01WebTest.setAac001("1");
        ac01WebTest.setAac002("1");
        ac01WebTest.setAac003("1");

        //增
        result = ac01WebTestDao.insertAc01WebTest();
        if(result == 0){
            throw new RuntimeException("没有插入任何数据");
        }
        //测试事务是否控制
        int i = 1/0;
        //删
        result = ac01WebTestDao.deleteAc01WebTest();
        if(result == 0){
            throw new RuntimeException("没有删除任何数据");
        }
        return result;
    }
}

4、核心:spring配置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"
       xmlns:context="http://www.springframework.org/schema/context"
       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-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd">

    <!--读取配置文件-->
    <context:property-placeholder location="classpath:db.properties"/>
    <!--配置数据源-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName">
            <value>${test_driver}</value>
        </property>
        <property name="url">
            <value>${test_url}</value>
        </property>
        <property name="username">
            <value>${test_username}</value>
        </property>
        <property name="password">
            <value>${test_password}</value>
        </property>
    </bean>
    <!--配置JDBC模板 -->
    <bean id="jdbcTemplate"
          class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <!--配置事务管理器-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <!--配置事务的属性-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <!--数据操作的所有方法都增加事务控制-->
            <tx:method name="*" read-only="false" propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice>
    <!--配置aop-->
    <aop:config>
        <!--配置切点表达式:service.impl下的所有类的所有参保类型的所有方法-->
        <aop:pointcut id="pt1" expression="execution(* com.a.service.impl.*.*(..))"/>
        <!--配置切点表达式和事务通知的对应关系-->
        <aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"/>
    </aop:config>

    <!--设置父属性模板-->
    <bean id="publicVar" abstract="true">
        <property name="error" value="0"/>
        <!--<property name="ok" value="1"/>-->
    </bean>
    <!--加载bean-->
    <bean id="ac01WebTest" class="com.a.entity.Ac01WebTest"/>
    <!--bean的继承-->
    <bean id="ac01WebTestResult" class="com.a.entity.Ac01WebTest" scope="prototype"/>
    <!--按类名自动装配-->
    <bean id="ac01WebTestDao" class="com.a.db.impl.Ac01WebTestDaoImpl" parent="publicVar" autowire="byName"/>
    <bean id="ac01WebTestService" class="com.a.service.impl.Ac01WebTestServiceImpl" autowire="byName"/>
</beans>

5、编写测试类

@Test
public void testMyjdbcUtil() throws Exception {
	ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
	Ac01WebTestService ac01WebTestService = context.getBean("ac01WebTestService",Ac01WebTestService.class);
	ac01WebTestService.modefyAc01WebTest();
}

八、参考资料

Spring框架教程(非常详细)Java Spring框架是为了解决企业应用程序开发的复杂性而创建的一个开源框架。Java Spring常用于来整合其他框架使用。这套Spring入门教程对Spring框架进行详细讲解,并且还提供了大量练习实例,以帮助读者快速入门学习。http://c.biancheng.net/spring/Spring JDBC配置与使用_木夆的博客-CSDN博客_springjdbc学习目标1.Spring JDBC模块有什么作用?1.1JdbcTemplate的解析1.2Spring Jdbc的配置1.3Spring JdbcTemplate的常用方法1.3.1创建数据库,并导入jar包1.3.2创建配置文件<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://ww...https://blog.csdn.net/weixin_44117272/article/details/94716724spring框架:简述JdbcTemplate及事务控制_灰灰渣的博客-CSDN博客_jdbctemplate事务控制本人小白一枚,欢迎大家一起讨论学习,如有错误,还望大家指教。简述JdbcTemplateJdbcTemplate概述它是spring框架中提供的一个对象,是对原始JDBC API对象的简单封装。spring框架为我们提供了很多操作模板类。操作关系型数据库的JdbcTemplate和HibernateTemplate,操作nosql数据库的RedisTemplate以及操作消息队列的Jms...https://blog.csdn.net/qq_43138206/article/details/105756655

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值