jdbc为java开发者提供了操作数据库标准的一系列API
越来越多的orm框架让我们逐渐忘记基本的jdbc操作,java没有帮助我们把一些基本步骤封装进去,需要我们自己去写一些步骤过程或者orm帮我们封装好。
1.jdbc基本步骤
- 加载对应数据库的jdbc驱动
- 连接对应的数据库
- 获取对应数据库的连接
- 创建statment对象
- 拼装需要执行的sql语句
- 执行sql
- 处理sql执行的结果
关闭相应的资源
如果执行的sql比较复杂,比如条件查询,有时候某个条件存在,有时候又不存在,这样代码逻辑上会增加一些代码量。
就需要我们进行相应的封装,将一些驱动加载,关闭连接等公共部分进行封装,sql拼装进行优化,以及代码分层。
package com.yangs.jdbc;
import javax.sql.RowSet;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
/**
* 一些orm学习之前,我们都需要了解基本jdbc的基本功,
* 这样我们才能体会到orm框架的好处,
* Created by Ytadpole on 2018/2/16.
*/
public class Jdbc {
public static void main(String[] args) throws SQLException {
//数据库信息
String username = "root";
String password = "password";
//条件查询
String name = "";
String description = "阿羊";
Connection conn = null;
PreparedStatement statement = null;
ResultSet set = null;
try {
//加载数据库
Class.forName("com.mysql.cj.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/jdbc?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC", username, password);
//sql语句以及参数准备
StringBuilder sql = new StringBuilder("select id, name, description from t_info where 1 = 1 ");
List<String> params = new ArrayList<>();
System.out.print("查询条件:");
if( null != name && !"".equals(name) ){
sql.append("and name = ?");
params.add(name);
System.out.print(" name = " + name + "| ");
}
if( null != description && !"".equals(description) ){
sql.append("and description like '%' ? '%'");
params.add(description);
System.out.print(" description like " + description );
}
//执行准备
statement = conn.prepareStatement(sql.toString());
for (int i = 0; i < params.size(); i++){
statement.setString( i + 1, params.get(i));
}
System.out.println("\n查询结果");
set = statement.executeQuery();
while(set.next()){
System.out.println(
set.getInt("id") +
": " + set.getString("name") +
": " + set.getString("description")
);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}finally {
//关闭连接
try {
set.close();
} catch (SQLException e) {
e.printStackTrace();
}
statement.close();
conn.close();
}
}
}
数据库数据
条件模糊查询 description 为 阿羊
条件查询 name为 阿羊