1.jdbc程序
使用jdbc查询mysql数据库中用户表的记录:
1)创建java工程,加入jar包:
2)数据库驱动包(mysql5.1)
3)mysql-connector-java-5.1.7-bin.jar
4)代码示例
package mybatis.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* jdbc编程步骤:
* 1、 加载数据库驱动
2、 创建并获取数据库链接
3、 创建jdbc statement对象
4、 设置sql语句
5、 设置sql语句中的参数(使用preparedStatement)
6、 通过statement执行sql并获取结果
7、 对sql执行结果进行解析处理
8、 释放资源(resultSet、preparedstatement、connection)
* @author Administrator
*
*/
public class JDBCTest {
public static void main(String args[]){
Connection connection=null;
PreparedStatement preparedStatement=null;
ResultSet resultSet=null;
try {
Class.forName("com.mysql.jdbc.Driver");
connection=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/zhenai?charaterEncoding=utf-8", "root", "root");
String sql="select * from user where loginname =?";
preparedStatement=connection.prepareStatement(sql);
preparedStatement.setString(1, "xiaoming");
resultSet=preparedStatement.executeQuery();
while(resultSet.next()){
System.out.println(resultSet.getString(1)+" "+resultSet.getString(2));
}
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}finally{
if(resultSet!=null){
try {
resultSet.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(preparedStatement!=null){
try {
preparedStatement.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(connection!=null){
try {
preparedStatement.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
5)问题总结:
1、数据库连接,使用时就创建,不使用立即释放,对数据库进行频繁连接开启和关闭,造成数据库资源浪费,影响 数据库性能。 设想:使用数据库连接池管理数据库连接。 2、将sql语句硬编码到java代码中,如果sql 语句修改,需要重新编译java代码,不利于系统维护。 设想:将sql语句配置在xml配置文件中,即使sql变化,不需要对java代码进行重新编译。 3、向preparedStatement中设置参数,对占位符号位置和设置参数值,硬编码在java代码中,不利于系统维护。 设想:将sql语句及占位符号和参数全部配置在xml中。 4、从resutSet中遍历结果集数据时,存在硬编码,将获取表的字段进行硬编码,,不利于系统维护。 设想:将查询的结果集,自动映射成java对象。
2 mybatis框架
2.1 mybatis是什么?
mybatis是一个持久层的框架,是apache下的顶级项目。
mybatis托管到goolecode下,再后来托管到github下(https://github.com/mybatis/mybatis-3/releases)。mybatis让程序将主要精力放在sql上,通过mybatis提供的映射方式,自由灵活生成(半自动化,大部分需要程序员编写sql)满足需要sql语句。
mybatis可以将向 preparedStatement中的输入参数自动进行输入映射,将查询结果集灵活映射成java对象。(输出映射)
2.2 mybatis框架
3 入门程序
3.1 环境
mybatis运行环境(jar包): 从https://github.com/mybatis/mybatis-3/releases下载
mybatis-3.2.7.jar:核心 包
mybatis-3.2.7.pdf,操作指南
加入mysql的驱动包
3.2 log4j.properties 工程结构
# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
3.3 SqlMapConfig.xml
配置mybatis的运行环境,数据源、事务等。
<?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>
<!-- SqlMapConfig.xml是mybatis核心配置文件,下面文件的配置内容为数据源、事务管理。 -->
<!-- 和spring整合后 environments配置将废除-->
<environments default="development">
<environment id="development">
<!-- 使用jdbc事务管理-->
<transactionManager type="JDBC" />
<!-- 数据库连接池-->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/zhenai?characterEncoding=utf-8"/>
<property name="username" value="root" />
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<!-- 在sqlMapConfig.xml中加载userMapper.xml: -->
<mappers>
<mapper resource="sqlmap/userMapper.xml"/>
</mappers>
</configuration>
3.4 根据用户id(主键)查询用户信息
3.4.1 创建po类
package mybatis.po;
public class User {
private String uid;
private String loginname;
private String password;
private String nickname;
private String sex;
private int age;
...
get/set
3.4.2 映射文件
映射文件命名:
User.xml(原始ibatis命名),mapper代理开发映射文件名称叫XXXMapper.xml,比如:UserMapper.xml、ItemsMapper.xml
在映射文件中配置sql语句。
<?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">
<!--namespace命名空间,作用就是对sql进行分类化管理,理解sql隔离
注意:使用mapper代理方法开发,namespace有特殊重要的作用
-->
<mapper namespace="test">
<!--在映射文件中配置很多sql语句 -->
<!--需求:通过id查询用户表的记录 -->
<!--通过select执行数据库查询
id:标识映射文件中的sql
将sql语句封装到mappedStatement对象中,所以将id称为statement的id
parameterType:指定输入参数的类型,这里指定int型
#{}表示一个占位符
#{id}:其中的id表示接受输入的参数,参数名称就是id,如
果输入参数是简单类型,#{}中的参数名可以任意,可以value或其他名称
resultType:指定sql输出结果的所映射的java对象类型,select指定resultType表示将单条记录映射成的java对象
-->
<select id="findUserById" parameterType="int" resultType="mybatis.po.User">
select * from user where uid=#{id}
</select>
</mapper>
3.4.3 程序测试
@Test
public void findUserByIdTest() throws IOException{
//mybatis配置文件
String resource="SqlMapConfig.xml";
//得到配置文件流
InputStream inputStream=Resources.getResourceAsStream(resource);
//创建会话工厂,传入mybatis的配置文件信息
SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
//通过工厂得到SqlSession
SqlSession sqlSession=sqlSessionFactory.openSession();
//通过SqlSession操作数据库
//第一个参数:映射文件statement的id,等于=namespace+"."+statement的id
//第二个参数:指定和映射文件中所匹配的parameterType类型的参数
//sqlSession.selectOne结果 是与映射文件中所匹配的resultType类型的对象
User user=sqlSession.selectOne("test.findUserById",1);
System.out.println(user);
//释放资源
sqlSession.close();
}