Spring 和 mysql数据库的连接及测试--Jdbc

来源:互联网 发布:哪里有呼死你软件出售 编辑:程序博客网 时间:2024/06/05 11:03

普遍的开发中, 通常使用会用到Spring框架和Mysql数据库 , 下面分享个人的Mysql在Spring中的配置以及它的连接测试.

本人在开发中 , 使用的是Maven管理工具 .  ( 关于Maven百度有详细安装配置教程,  )

一. 创建Maven Web  的java工程(  本人前面有文章讲过创建Maven Web项目 ), 创建完成后在pom.xml中加入mysql驱动相关的jar包

pom.xml中的配置为: 

<!-- 数据库驱动 --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.38</version></dependency><!--spring对jdbc的支持包 --><dependency><groupId>org.springframework</groupId><artifactId>spring-jdbc</artifactId><version>${spring.version}</version></dependency><!-- spring连接数据库 --><dependency><groupId>org.springframework</groupId><artifactId>spring-jdbc</artifactId><version>4.3.2.RELEASE</version></dependency><!-- spring测试包 --><dependency><groupId>org.springframework</groupId><artifactId>spring-test</artifactId><version>4.3.2.RELEASE</version></dependency><!-- springMVC --><dependency><groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId><version>4.3.2.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-context-support</artifactId><version>4.3.2.RELEASE</version></dependency>

配置db.properties: ( 这里的属性值可以直接写入spring.xml中  ,与 ${ } 的值相对应)

#在这里如果引入的mysql jar包为6.0版本 , 驱动值为 :  com.mysql.cj.jdbc.Driverjdbc.driverClassName=com.mysql.jdbc.Driverjdbc.url=jdbc:mysql://localhost:3306/usersystemjdbc.username=rootjdbc.password=111

spring.xml中的配置为:

<!-- 引入外部的属性文件 -->    <context:property-placeholder location="classpath:db.properties"/><!-- jdbc连接设置 --><bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"><property name="driverClassName" value="${jdbc.driverClassName}" /><property name="url" value="${jdbc.url}" /><property name="username" value="${jdbc.username}" /><property name="password" value="${jdbc.password}" /></bean>

创建一个测试类: ConnTest.java

package com.lsy.conn.test;import static org.junit.Assert.assertNotNull;import java.sql.Connection;import java.sql.SQLException;import javax.sql.DataSource;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.test.context.ContextConfiguration;import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration("classpath:spring.xml")public class ConnTest {@Autowiredprivate DataSource dataSource;@Testpublic void testConn() {Connection con = null;try {con = dataSource.getConnection();} catch (SQLException e) {throw new RuntimeException("连接失败!!!", e);}assertNotNull(con);}}

祝大家配置成功!!!



原创粉丝点击