Spring连接数据库的几种常用的方式

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

测试主类为:

package myspring2;

import java.sql.*;

import javax.sql.DataSource;

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext; public class MySpringTest {

public static void main(String args[]) throws Exception{

ApplicationContext ctx=new

ClassPathXmlApplicationContext("applicationContext.xml");

DataSource dataSource=ctx.getBean("dataSource",DataSource.class);

String sql="select * from user_inf";

Connection connection=dataSource.getConnection();

Statement stm=connection.createStatement();

ResultSet rs=stm.executeQuery(sql);

while(rs.next())

{ System.out.println("用户名为:");

System.out.println(rs.getString(2));

}

}

}

第一种:使用spring自带的DriverManagerDataSource 配置文件如下:

xmlns:aop="/schema/aop"

xmlns:tx="/schema/tx"

xmlns:xsi="/2001/XMLSchema-instance"

xmlns:context="/schema/context"

xmlns:p="/schema/p"

xsi:schemaLocation="

/schema/beans

/schema/beans/spring-beans-3.0.xsd

/schema/tx

/schema/tx/spring-tx-3.0.xsd

/schema/context

/schema/context/spring-context-3.0.xsd

/schema/aop

/schema/aop/spring-aop-3.0.xsd">

name="dataSource" class="org.springframework.jdbc.datasource.DriverManager DataSource"

p:driverClassName="com.mysql.jdbc.Driver"

p:url="jdbc:mysql://localhost:3306/test"

p:username="root"

p:password="123456" / >

第二种:C3P0数据源。

需要使c3p0的核心jar包,我使用的是c3p0-0.9.1.jar,比较稳定,推荐使用。一般在下载hibernate的时候都会自带一个:我在hibernate-release-4.3.0.Final\lib\optional\c3p0路径下找到的。

配置文件中如下:

xmlns:aop="/schema/aop"

xmlns:tx="/schema/tx"

xmlns:xsi="/2001/XMLSchema-instance"

xmlns:context="/schema/context"

xmlns:p="/schema/p"

xsi:schemaLocation="

/schema/beans

/schema/beans/spring-beans-3.0.xsd /schema/tx

/schema/tx/spring-tx-3.0.xsd

/schema/context

/schema/context/spring-context-3.0.xsd

/schema/aop

/schema/aop/spring-aop-3.0.xsd">

class="boPooledDataSource"

p:driverClass="com.mysql.jdbc.Driver"

p:jdbcUrl="jdbc:mysql://localhost:3306/test"

p:user="root"

p:password="123456" >

相关文档
最新文档