1. 程式人生 > >Spring 和 mysql資料庫的連線及測試--Jdbc

Spring 和 mysql資料庫的連線及測試--Jdbc

普遍的開發中, 通常使用會用到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.Driver
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/usersystem
jdbc.username=root
jdbc.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 {
	
	@Autowired
	private DataSource dataSource;
	
	@Test
	public void testConn() {
		Connection con = null;
		try {
			con = dataSource.getConnection();
		} catch (SQLException e) {
			throw new RuntimeException("連線失敗!!!", e);
		}
		assertNotNull(con);
	}
	
}

祝大家配置成功!!!