【maven+spring+mysql】数据源配置

引用

【maven+spring+mysql】数据源配置

1.mavenpom.xml中添加

<!-- MySql -->
	<dependency>
	  <groupId>mysql</groupId>
	  <artifactId>mysql-connector-java</artifactId>
	  <version>5.1.30</version>
	</dependency>
	
	<!-- DBCP -->
	<dependency>
	  <groupId>commons-dbcp</groupId>
	  <artifactId>commons-dbcp</artifactId>
	  <version>1.4</version>
	</dependency>

2.配置数据源(DBCP)

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
       		<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
       		<property name="url" value="jdbc:mysql://localhost/test" />
       		<property name="username" value="root" />
       		<property name="password" value="1111" />
       		<property name="initialSize" value="5" />
       		<property name="maxActive" value="10" />
       </bean>

3.连接测试

package com.lh.springtest02.section5;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.sql.DataSource;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
 
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:section5/testDB.xml"})

public class JdbcTestDB {

	   @Autowired
	   @Qualifier("dataSource")
	   private DataSource dataSource;
	   private static final String STUDENT_SEARCH = "select * from student";
	   
	   @Test
	   public void searchPerson() {
		   Connection conn = null;
		   PreparedStatement ps = null;
		   ResultSet rs = null;
		   Map psMap = null;
		   List psList = new ArrayList();
		   try {
			   conn = dataSource.getConnection();
			   
			   ps = conn.prepareStatement(STUDENT_SEARCH);
			   rs = ps.executeQuery(STUDENT_SEARCH);
			   while(rs.next()) {
				   psMap = new HashMap();
				   psMap.put("id", rs.getInt("id"));
				   psMap.put("name", rs.getString("name"));
				   psMap.put("age", rs.getInt("age"));
				   psList.add(psMap);
			   }
			   System.out.println(psList);
		   } catch(SQLException e) {
			   e.printStackTrace();
		   }
	   }
}

相关推荐