在eclipse中使用JDBC连接MySQL5.7.24
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]
注意:版本问题,各个版本要匹配。