eclipse版本:eclipse4.10.0 。jdk1.8。如圖1:
mysql版本:mysql-5.7.24-winx64
JDBC連接池c3p0版本:c3p0-0.9.5.2.jar
驅動:mysql-connector-java-8.0.16
eclipse下新建project->spring1->src->com.spring.beans.properties->Main.java
src下新建beans-properties.xml
spring1->lib,添加jar包,並選中這些jar包->右鍵->Build Path->Add to Build Path。樣這5個包就添加到了Referenced Libraries路徑下了。
如圖2:
beans-properties.xml 代碼如下:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="user" value="root"></property>
<property name="password" value="123456"></property>
<property name="driverClass" value="com.mysql.cj.jdbc.Driver"></property>
<property name="jdbcUrl">
<value>jdbc:mysql://localhost/mysql?useUnicode=true&characterEncoding=utf-8&useSSL=FALSE&serverTimezone=UTC</value>
</property>
</bean>
</beans>
對於jdbc:mysql://localhost/mysql第二個"mysql"表示數據庫名字是mysql,這點可以通過以下步驟查看:
1. cmd下進入mysql安裝目錄的bin文件夾下,比如cd D:\mysql\mysql-5.7.24-winx64\bin
2. 輸入:mysql -uroot -p,然后是password
3. 輸入: show databases; 會顯示所有的數據庫,如圖3
Main.java代碼如下:
import java.sql.SQLException;
import javax.sql.DataSource;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String[] args) throws SQLException {
ApplicationContext ctx=new ClassPathXmlApplicationContext("beans-properties.xml");
DataSource dataSource=(DataSource) ctx.getBean("dataSource");
System.out.println(dataSource.getConnection());
}
}
開始->services.msc,找到mysql,運行程序之前請啟動mysql服務。如圖4:
運行Main.java輸出下面一行表示連接數據庫成功:
com.mchange.v2.c3p0.impl.NewProxyConnection@6cc7b4de [wrapping: com.mysql.cj.jdbc.ConnectionImpl@32cf48b7]
注意:版本問題,各個版本要匹配。