1.普通JDBC 连接数据库(以MySQL为例)
Class.forName("com.mysql.jdbc.Driver");//加载驱动
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306//springboot");//获取连接
String sql = "select * from user"
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(sql);//创建sql并发送sql语句
- Mybatis框架连接数据库
2.1 一般使用属性文件 属性文件的优点:修改属性文件时无需重启服务器
database.driver=com.mysql.jdbc.Driver//驱动地址
database.url=jdbc:mysql://localhost:3306/springboot?useSSL=false//数据库地址
database.username=root//用户名
database.password=sa//密码
2.2附上主配置文件 mybatis.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!--引入数据库连接属性文件-->
<properties resource="database.properties"></properties>
<!--配置数据库环境,一般配置一个开发环境和一个生产环境-->
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<!-- 使用了属性文件的内容-->
<property name="driver" value="${database.driver}"/>
<property name="url" value="${database.url}"/>
<property name="username" value="${database.username}"/>
<property name="password" value="${database.password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<!--映射文件地址-->
<mapper resource="UserMapper.xml"/>
</mappers>
</configuration>
2.3 附上副配置文件 UserMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="实体类接口地址">
<select id="selectAll" resultType="Map">
select * from user
</select>
</mapper>
- Mybatis 框架的使用
<!-- 1、获取SqlSession对象-->
InputStream inputStream = Resources.getResourceAsStream("myBatis.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
<!-- 2、调用相应方法 -->
User user = (User)sqlSession.selectOne("getUser",1);
<!--selectOne是方法名 ‘1’是参数值 -->
网友评论