Spring简单与数据库连接
1、导入需要的jar包
2、配置数据源,在applicationContext.xml文件中增加配置
方式1:直接使用bean方式
1 2 3 4 5 6 | < bean id = "dataSource" class = "org.apache.commons.dbcp.BasicDataSource" destroy-method = "close" > < property name = "driverClassName" value = "com.mysql.jdbc.Driver" /> < property name = "username" value = "root" /> < property name = "password" value = "root" /> </ bean > |
方式2:使用properties文件
在src下新建jdbc.properties文件,内容如下:
1 2 3 4 | jdbc.driverClassName=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql: //localhost:3306/test jdbc.username=root jdbc.password=root |
applicationContext.xml
1 2 3 4 5 6 7 8 9 10 11 | < bean class = "org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" > < property name = "locations" value = "classpath:jdbc.properties" /> </ bean > < bean id = "dataSource" destroy-method = "close" class = "org.apache.commons.dbcp.BasicDataSource" > < 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 > |
3、测试连接数据库
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | package com.fz.annotation.dao.impl; import java.sql.Connection; import java.sql.SQLException; import javax.annotation.Resource; import javax.sql.DataSource; import org.springframework.stereotype.Repository; import com.fz.annotation.dao.UserDao; import com.fz.xml.entity.User; @Repository ( "userDao" ) public class UserDaoImpl implements UserDao{ private DataSource dataSource; public void userAdd(User user) { Connection conn = null ; try { conn = dataSource.getConnection(); conn.createStatement().executeUpdate( "insert into user values(null,'张三')" ); } catch (Exception e) { e.printStackTrace(); } finally { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } public DataSource getDataSource() { return dataSource; } @Resource public void setDataSource(DataSource dataSource) { this .dataSource = dataSource; } } |