JDBC
JDBC,即Java Database Connectivity,java数据库连接。
是一种用于执行SQL语句的Java API,它是 Java中的数据库连接规范。
JDBC 工作原理
JDBC访问数据库层次结构:
JDBC优势:
- Java语言访问数据库操作完全面向抽象接口编程
- 开发数据库应用不用限定在特定数据库厂商的API
- 程序的可移植性大大增强
JDBC使用
JDBC开发案例:
- 建立数据库连接
// 加载JDBC驱动程序:反射,这样调用初始化com.mysql.jdbc.Driver类,
// 即将该类加载到JVM方法 区,并执行该类的静态方法块、静态属性。
Class.forName("com.mysql.jdbc.Driver");
// 创建数据库连接
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test? user=root&password=root&useUnicode=true&characterEncoding=UTF-8");
//MySQL数据连接的URL参数格式如下:
jdbc:mysql://服务器地址:端口/数据库名?参数名=参数值
- 创建操作命令(Statement)
Statement statement = connection.createStatement();
- 执行SQL语句
ResultSet resultSet= statement.executeQuery(
"select id, sn, name, qq_mail, classes_id from student");
- 处理结果集
while (resultSet.next()) {
int id = resultSet.getInt("id");
String sn = resultSet.getString("sn");
String name = resultSet.getString("name");
int classesId = resultSet.getInt("classes_id");
System.out.println(String.format("Student: id=%d, sn=%s, name=%s, classesId=%s", id, sn, name, classesId));
}
- 释放资源(关闭结果集,命令,连接)
//关闭结果集
if (resultSet!= null) {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
//关闭命令
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
// 关闭连接命令
if (connection!= null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
JDBC使用步骤总结:
- 创建数据库连接Connection
- 创建操作命令Statement
- 使用操作命令来执行SQL
- 处理结果集ResultSet
- 释放资源
JDBC API
数据库连接Connection:
Connection接口实现类由数据库提供,获取Connection对象通常有两种方式:
- 通过DriverManager(驱动管理类)的静态方法获取:
// 加载JDBC驱动程序
Class.forName("com.mysql.jdbc.Driver");
// 创建数据库连接
Connection connection = DriverManager.getConnection(url);
- 通过DataSource(数据源)对象获取。
DataSource ds = new MysqlDataSource();
((MysqlDataSource) ds).setUrl("jdbc:mysql://localhost:3306/test");
((MysqlDataSource) ds).setUser("root");
((MysqlDataSource) ds).setPassword("root");
Connection connection = ds.getConnection();
以上两种方式的区别是:
- DriverManager类来获取的Connection连接,是无法重复利用的,每次使用完以后释放资源时,通过 connection.close() 都是关闭物理连接。
- DataSource提供连接池的支持。连接池在初始化时将创建一定数量的数据库连接,这些连接 是可以复用的,每次使用完数据库连接,释放资源调用connection.close()都是将 Conncetion连接对象回收。
Statement对象
Statement 对象主要是将SQL语句发送到数据库中。
PreparedStatement对象:
两种执行SQL的方法:
- executeQuery() 方法执行后返回单个结果集的,通常用于select语句。
- executeUpdate()方法返回值是一个整数,指示受影响的行数,通常用于update、insert、delete 语句。
ResultSet对象
ResultSet对象它被称为结果集,它代表符合SQL语句条件的所有行,并且它通过一套getXXX方法提供 了对这些行中数据的访问。
ResultSet里的数据一行一行排列,每行有多个字段,并且有一个记录指针,指针所指的数据行叫做当前数据行,我们只能来操作当前的数据行。我们如果想要取得某一条记录,就要使用ResultSet的next() 方法,如果我们想要得到ResultSet里的所有记录,就应该使用while循环。
重点总结
JDBC使用步骤
- 创建数据库连接Connection
DriverManager创建
DataSource获取 - 创建操作命令Statement
PreparedStatement - 使用操作命令来执行SQL
// 查询操作
preparedStatement.executeQuery();
// 新增、修改、删除操作
preparedStatement.executeUpdate();
- 处理结果集ResultSet
while (resultSet.next()) {
int xxx = resultSet.getInt("xxx");
String yyy= resultSet.getString("yyy");
...
}
- 释放资源
try {
if(resultSet != null){
resultSet.close();
}
if(preparedStatement != null){
preparedStatement.close();
}
if(connection != null){
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException("数据库错误");
}
public class DbUtil {
public static final String URL = "jdbc:mysql://localhost:3306/imooc";
public static final String USER = "liulx";
public static final String PASSWORD = "123456";
public static void main(String[] args) throws Exception {
//1.加载驱动程序
Class.forName("com.mysql.jdbc.Driver");
//2. 获得数据库连接
Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);
//3.操作数据库,实现增删改查
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT user_name, age FROM imooc_goddess");
//如果有数据,rs.next()返回true
while(rs.next()){
System.out.println(rs.getString("user_name")+" 年龄:"+rs.getInt("age"));
}
}
}
实例
public class DbUtil {
public static final String URL = "jdbc:mysql://localhost:3306/imooc";
public static final String USER = "liulx";
public static final String PASSWORD = "123456";
private static Connection conn = null;
static{
try {
//1.加载驱动程序
Class.forName("com.mysql.jdbc.Driver");
//2. 获得数据库连接
conn = DriverManager.getConnection(URL, USER, PASSWORD);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
public static Connection getConnection(){
return conn;
}
}
//模型
public class Goddess {
private Integer id;
private String user_name;
private Integer sex;
private Integer age;
private Date birthday; //注意用的是java.util.Date
private String email;
private String mobile;
private String create_user;
private String update_user;
private Date create_date;
private Date update_date;
private Integer isDel;
//getter setter方法。。。
}
//---------dao层--------------
public class GoddessDao {
//增加
public void addGoddess(Goddess g) throws SQLException {
//获取连接
Connection conn = DbUtil.getConnection();
//构建sql
String sql = "INSERT INTO imooc_goddess(user_name, sex, age, birthday, email, mobile,"+
"create_user, create_date, update_user, update_date, isdel)"
+"values("+"?,?,?,?,?,?,?,CURRENT_DATE(),?,CURRENT_DATE(),?)";
//预编译SQL,减少sql执行
PreparedStatement ptmt = conn.prepareStatement(sql);
//传参
ptmt.setString(1, g.getUser_name());
ptmt.setInt(2, g.getSex());
ptmt.setInt(3, g.getAge());
ptmt.setDate(4, new Date(g.getBirthday().getTime()));
ptmt.setString(5, g.getEmail());
ptmt.setString(6, g.getMobile());
ptmt.setString(7, g.getCreate_user());
ptmt.setString(8, g.getUpdate_user());
ptmt.setInt(9, g.getIsDel());
//执行
ptmt.execute();
}
//修改
public void updateGoddess(){
//获取连接
Connection conn = DbUtil.getConnection();
//sql, 每行加空格
String sql = "UPDATE imooc_goddess" +
" set user_name=?, sex=?, age=?, birthday=?, email=?, mobile=?,"+
" update_user=?, update_date=CURRENT_DATE(), isdel=? "+
" where id=?";
//预编译SQL,减少sql执行
PreparedStatement ptmt = conn.prepareStatement(sql);
//传参
ptmt.setString(1, g.getUser_name());
ptmt.setInt(2, g.getSex());
ptmt.setInt(3, g.getAge());
ptmt.setDate(4, new Date(g.getBirthday().getTime()));
ptmt.setString(5, g.getEmail());
ptmt.setString(6, g.getMobile());
ptmt.setString(7, g.getUpdate_user());
ptmt.setInt(8, g.getIsDel());
ptmt.setInt(9, g.getId());
//执行
ptmt.execute();
}
//删除
public void delGoddess(){
//获取连接
Connection conn = DbUtil.getConnection();
//sql, 每行加空格
String sql = "delete from imooc_goddess where id=?";
//预编译SQL,减少sql执行
PreparedStatement ptmt = conn.prepareStatement(sql);
//传参
ptmt.setInt(1, id);
//执行
ptmt.execute();
}
//查询
public List<Goddess> query() throws SQLException {
Connection conn = DbUtil.getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT user_name, age FROM imooc_goddess");
List<Goddess> gs = new ArrayList<Goddess>();
Goddess g = null;
while(rs.next()){
g = new Goddess();
g.setUser_name(rs.getString("user_name"));
g.setAge(rs.getInt("age"));
gs.add(g);
}
return gs;
}
public Goddess get(){
Goddess g = null;
//获取连接
Connection conn = DbUtil.getConnection();
//sql, 每行加空格
String sql = "select * from imooc_goddess where id=?";
//预编译SQL,减少sql执行
PreparedStatement ptmt = conn.prepareStatement(sql);
//传参
ptmt.setInt(1, id);
//执行
ResultSet rs = ptmt.executeQuery();
while(rs.next()){
g = new Goddess();
g.setId(rs.getInt("id"));
g.setUser_name(rs.getString("user_name"));
g.setAge(rs.getInt("age"));
g.setSex(rs.getInt("sex"));
g.setBirthday(rs.getDate("birthday"));
g.setEmail(rs.getString("email"));
g.setMobile(rs.getString("mobile"));
g.setCreate_date(rs.getDate("create_date"));
g.setCreate_user(rs.getString("create_user"));
g.setUpdate_date(rs.getDate("update_date"));
g.setUpdate_user(rs.getString("update_user"));
g.setIsDel(rs.getInt("isdel"));
}
return g;
}
}