Spring簡單與數據庫鏈接

一、導入須要的jar包java


二、配置數據源,在applicationContext.xml文件中增長配置mysql

方式1:直接使用bean方式
spring

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 = "url" value = "jdbc:mysql://localhost:3306/test" />
     < property name = "username" value = "root" />
     < property name = "password" value = "root" />
</ bean >

方式2:使用properties文件sql

在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.xmlapache

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 >


三、測試鏈接數據庫app

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;
     }
 
}






相關文章
相關標籤/搜索