本文讲的是使用spring自带的DriverManagerDataSource 来实现数据库的连接。
创建测试主类MySpringTest
package Myspring;
import java.sql.*;
import javax.sql.DataSource;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* @author zhenqingshi
*
* 2018年7月6日
*/
public class MySpringTest {
@SuppressWarnings("resource")//该批注的作用是给编译器一条指令,告诉它对被批注的代码元素(ctx)内部的某些警告保持静默。详见另一篇博文:地址
public static void main(String args[]) throws Exception{
ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml"); //加载spring配置文件
DataSource dataSource=ctx.getBean("dataSource",DataSource.class);//加载数据库驱动类
String sql="select * from Student"; //查询表为Student,已在数据库创建
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));
}
}
}
applicationContext.xml代码为:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
<!-- 使用XML Schema的p名称空间配置 -->
<bean name="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"
p:driverClassName="com.mysql.jdbc.Driver"
p:url="jdbc:mysql://localhost:3306/test"
p:username="root"
p:password="root" />
</beans>
目录结构为:
测试示意图:
遇到的主要错误:
Exception in thread "main" java.lang.UnsupportedClassVersionError: com/mysql/jdbc/Driver : Unsupported major.minor version 52.0?
Exception in thread "main" java.lang.UnsupportedClassVersionError: com/mysql/jdbc/Driver : Unsupported major.minor version 52.0
原因: 主要是jdk版本和MySQL驱动包兼容错误
1、jdk7+老版5.0驱动com/mysql/jdbc/Driver (这里使用的是jdk7,所以重新下了个MySQL驱动包5.1.10的,替换后就行了)
2、jdk8+新版6.0驱动com/mysql/cj/jdbc/Driver
附:spring4.2.3.jar,mysql-connector-java-5.1.10.jar和org.springframework.jdbc-3.2.2.RELEASE.jar下载地址:
链接:https://pan.baidu.com/s/1RNZQsg5Hf4LRSjTFshWHvA 密码:5wzd
mysql-connector-java-6.0.2.jar下载地址:
链接:https://pan.baidu.com/s/1U71Kf7SslFeePL4pQh2sPA 密码:vzhw
最后附上spring连接数据库的其他几种方式:
https://www.cnblogs.com/xiohao/p/3663619.html