传统的 jdbc :
/**
* 加载数据库驱动
* 创建并获取数据库连接
* 创建jdbc statement对象
* 编写sql语句
* 设置sql语句中的参数(使用PreStatement)
* 通过statement执行sql并获取结果
* 对sql执行结果进行解析处理
* 释放资源(resultSet,preparedstatement,connection)
*
*/
Connection con=null;
PreparedStatement ps=null;
ResultSet rs=null;
try {
Class.forName("com.mysql.jdbc.Driver");
con=(Connection) DriverManager.getConnection("jdbc:mysql///mybatis", "root", "981012");
String sql="select * from user where id=?";
ps=(PreparedStatement) con.prepareStatement(sql);
ps.setInt(1, 5);
rs= ps.executeQuery();
//处理结果
while(rs.next()) {
int id=rs.getInt(1);
String name=rs.getString(2);
//一个一个获取
System.out.println(id+"----"+name);
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
try {
if(con!=null) {
con.close();
}
if(ps!=null) {
ps.close();
}
if(rs!=null) {
rs.close();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Mybatis 框架:
文字解释:
搭建框架:
先创建 Mybatis 的核心配置文件 SqlMapConfig.xml ,然后在里面配置数据源和事务
然后创建需要的 mapper 文件
然后将 mapper 文件配置到 SqlMapConfig.xml 配置文件中
测试(Mybatis 的执行流程)