您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

spring连接数据库

bubuko 2022/1/25 19:06:47 java 字数 2738 阅读 759 来源 http://www.bubuko.com/infolist-5-1.html

连接测试 @Test public void test5() throws SQLException { //从容器中获取datasource对象 ApplicationContext applicationContext = new ClassPathXmlApplicationContext(" ...

连接测试

    @Test
    public void test5() throws SQLException {
        //从容器中获取datasource对象
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        DruidDataSource dataSource = applicationContext.getBean(DruidDataSource.class);
        DruidPooledConnection connection = dataSource.getConnection();
        System.out.println(connection);
        connection.close();
    }

jdbc.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/db1
jdbc.username=root
jdbc.password=root

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"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context  http://www.springframework.org/schema/context/spring-context.xsd
">
<!--    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">-->
<!--        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>-->
<!--        <property name="url" value="jdbc:mysql:///db1"/>-->
<!--        <property name="username" value="root"/>-->
<!--        <property name="password" value="root"/>-->
<!--    </bean>-->

<!--    加载配置文件-->
<!--    先配置context的命名空间,使用spring表达式-->
        <context:property-placeholder location="jdbc.properties"/>
        <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
            <property name="driverClassName" value="${jdbc.driver}"/>
            <property name="url" value="${jdbc.url}"/>
            <property name="username" value="${jdbc.username}"/>
            <property name="password" value="${jdbc.password}"/>
        </bean>
</beans>

spring连接数据库

原文:https://www.cnblogs.com/codegzy/p/14786620.html


如果您也喜欢它,动动您的小指点个赞吧

除非注明,文章均由 laddyq.com 整理发布,欢迎转载。

转载请注明:
链接:http://laddyq.com
来源:laddyq.com
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。


联系我
置顶