1.使用Gradle方式引入依赖
//引入测试依赖
testCompile 'junit:junit:4.12'
//引入spring依赖
implementation 'org.springframework:spring-context:5.1.5.RELEASE'
//引入mysql依赖
implementation 'mysql:mysql-connector-java:5.1.24'
//引入c3p0依赖
implementation 'c3p0:c3p0:0.9.1.2'
//引入druid依赖
implementation 'com.alibaba:druid:1.2.6'
2.创建数据源
2.1手动创建c3p0数据源
@Test
// 测试手动创建c3p0数据源
fun test1(){
val dataSource = ComboPooledDataSource()
dataSource.driverClass = "com.mysql.jdbc.Driver"
dataSource.jdbcUrl = "jdbc:mysql://localhost:3306/Server01"
dataSource.user = "root"
dataSource.password = "root"
val connection = dataSource.connection
println(connection)
connection.close()
}
2.2手动创建druid数据源
@Test
// 测试手动创建druid数据源
fun test2(){
val dataSource = DruidDataSource()
dataSource.driverClassName = "com.mysql.jdbc.Driver"
dataSource.url = "jdbc:mysql://localhost:3306/Server01"
dataSource.username = "root"
dataSource.password = "root"
val connection = dataSource.connection
println(connection)
connection.close()
}
2.3手动创建druid数据源(加载properties配置文件)(c3p0同理)
2.3.1 在resources目录下创建jdbc.properties配置文件
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/Server01
jdbc.username=root
jdbc.password=root
2.3.2 读取配置文件
@Test
测试手动创建druid数据源(加载properties配置文件)
fun test3(){
//读取配置文件
val rb = ResourceBundle.getBundle("jdbc")
val driver = rb.getString("jdbc.driver")
val url = rb.getString("jdbc.url")
val username = rb.getString("jdbc.username")
val password = rb.getString("jdbc.password")
val dataSource = DruidDataSource()
dataSource.driverClassName = driver
dataSource.url = url
dataSource.username = username
dataSource.password = password
val connection = dataSource.connection
println(connection)
connection.close()
}
2.4自动创建druid数据源(c3p0同理)
2.4.1 在resources目录下创建applicationContext.xml配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 加载配置文件 -->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!-- 自动配置数据源 -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!-- 注解的组件扫描 -->
<context:component-scan base-package="包名"/>
</beans>
2.4.4 引入applicationContext配置文件,测试
@Test
// 测试自动创建druid数据源
fun test4(){
val app = ClassPathXmlApplicationContext("applicationContext.xml")
val dataSource = app.getBean("dataSource") as DruidDataSource
val connection = dataSource.connection
println(connection)
connection.close()
}