详解各个对象
1.DriverManager :驱动管理对象
功能: 1.注册驱动:告诉程序该使用哪一个数据库驱动jar static void registerDriver(Driver driver) :注册与给定的驱动程序 DriverManager
写代码使用:class.forName( "com.mysql.jdbc.Driver" );
通过查看源码发现:在com.mysql.jdbc.Driver类中存在静态代码块
static { try { java.sql.DriverManager.registerDriver(new Driver());
}catch (SQLException E) { throw new RuntimeException( "can't register driver!"); } 注意: mysq15之后的驱动jar包可以省略注册驱动的步骤。
2.获取数据库连接
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/db2", "root", "root");
url:指定连接的路径
细节∶如果连接的是本机mysql服务器,并且mysql服务默认端口是3306,则url可以简写为:jdbc:mysql///数据库名
user:用户名
password:密码
2.connection :数据库连接对象
功能: 1.获取执行sql 的对象 statement createstatement() Preparedstatement preparestatement(string sql)
2.管理事务∶
开启事务: setAutoCommit(boolean autoCommit):调用该方法设置参数为false,即开启事务
提交事务: commit()
回滚事务:rollback()
3.statement :执行sql的对象
1.执行sql
- boolean execute(String sql) : 可以执行任意的sql,了解即可
- int executeUpdate(String sql) : 执行DML (insert、 update、 delete) 语句、DDL(create, alter、 drop)语句 返回值:影响的行数,可以通过这个影响的行数判断DML语句是否执行成功返回值>0的则执行成功,反之,则失败。
- ResultSet executeQuery(String sql) : 执行DQL (select)语句
2.练习
1.添加一条记录
2.修改记录
3.删除记录
为了代码健壮性,进行捕获异常
String sql = "update account set balance = 40 where id = 1"; String sql = "insert into account values(3,'ws',1002)"; String sql = "delete from account where id = 3";
修改后的代码
package cn.caq.jdbc; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; public class JdbcDemo03 { public static void main(String[] args) { Connection conn = null; Statement stmt = null; try { //1.注册驱动 Class.forName("com.mysql.jdbc.Driver"); //2.获取连接对象 conn = DriverManager.getConnection("jdbc:mysql:///db2", "root", "root"); //3.定义sql String sql = "insert into account values(3,'ws',1002)"; //4.获取执行sql对象 stmt = conn.createStatement(); //5.执行sql int count = stmt.executeUpdate(sql); //6.处理结果 System.out.println(count); if (count > 0){ System.out.println("修改成功"); }else { System.out.println("修改失败"); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException throwables) { throwables.printStackTrace(); } finally { if (stmt != null){ try { stmt.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } if (conn != null){ try { conn.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } } } }
4.Resultset :结果集对象
结果集对象,封装查询结果
1.next();游标向下移动一行,判断当前行是否是最后一行末尾
它的返回值是布尔值
2.getXXX:获取数据,XXX代表数据类型int getInt() String getString()
... //int :代表列的编号,从1开始 如:getString(1) //string: 代表列的名称 如:getString("name") int id = res.getInt(1); String name = res.getString("name"); double balance = res.getDouble(3); System.out.println(id + "---" + name + "---" + balance); 结果为: 1---zs---40.0
使用步骤:
- 游标向下移动一行
- 判断是否有数据
- 获取数据
正确用法
while (res.next()){ int id = res.getInt(1); String name = res.getString("name"); double balance = res.getDouble(3); System.out.println(id + "---" + name + "---" + balance); }
查询练习:
查询表的数据封装为对象,返回一个列表打印处理
思路:
定义一个方法,查询emp表的数据将其封装为对象,然后装载集合,返回
1.根据表的结构定义一个emp类
2.查询的结果封装为emp类的对象
3.定义方法public list findAll(){}查询表中数据并封装为集合
Emp类
package cn.caq.domain; import java.util.Date; /** * 封装Emp表数据的Java Bean */ public class Emp { private int id; private String ename; private int job_id; private int mgr; private Date joindate; private double salary; private double bounds; private int dept_id; public int getId() { return id; } public String getEname() { return ename; } public void setEname(String ename) { this.ename = ename; } public void setId(int id) { this.id = id; } public int getJob_id() { return job_id; } public void setJob_id(int job_id) { this.job_id = job_id; } public int getMgr() { return mgr; } public void setMgr(int mgr) { this.mgr = mgr; } public Date getJoindate() { return joindate; } public void setJoindate(Date joindate) { this.joindate = joindate; } public double getSalary() { return salary; } public void setSalary(double salary) { this.salary = salary; } public double getBounds() { return bounds; } public void setBounds(double bounds) { this.bounds = bounds; } public int getDept_id() { return dept_id; } public void setDept_id(int dept_id) { this.dept_id = dept_id; } @Override public String toString() { return "Emp{" + "id=" + id + ", ename='" + ename + '\'' + ", job_id=" + job_id + '}'; } }
查询方法
package cn.caq.jdbc; import cn.caq.domain.Emp; import java.sql.*; import java.util.ArrayList; import java.util.List; /** * 定义一个方法,查询emp表的数据将其封装为对象,然后装载集合,返回 */ public class JdbcDemo06 { public static void main(String[]args){ List<Emp> list = new JdbcDemo06().findall(); System.out.println(list); } public List<Emp> findall() { Connection conn = null; Statement stmt = null; ResultSet res = null; ArrayList<Emp> list = null; try { //1.注册驱动 Class.forName("com.mysql.jdbc.Driver"); //2.获取连接对象 conn = DriverManager.getConnection("jdbc:mysql:///db2", "root", "root"); //3.定义sql String sql = "select * from emp"; //4.获取执行sql对象 stmt = conn.createStatement(); //5.执行sql res = stmt.executeQuery(sql); //6.处理结果 Emp emp = null; list = new ArrayList<>(); while (res.next()) { int id = res.getInt("id"); String ename = res.getString("ename"); int job_id = res.getInt("job_id"); //创建emp对象,并赋值 emp = new Emp(); emp.setId(id); emp.setEname(ename); emp.setJob_id(job_id); //装载集合 list.add(emp); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException throwables) { throwables.printStackTrace(); } finally { if (stmt != null) { try { stmt.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } if (conn != null) { try { conn.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } if (res != null) { try { res.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } } return list; } } 输出结果为: [Emp{id=1001, ename='孙悟空', job_id=4}, Emp{id=1002, ename='卢俊义', job_id=3}, Emp{id=1003, ename='林冲', job_id=3}, Emp{id=1004, ename='唐僧', job_id=2}, Emp{id=1005, ename='李逵', job_id=4}, Emp{id=1006, ename='宋江', job_id=2}, Emp{id=1007, ename='刘备', job_id=2}, Emp{id=1008, ename='猪八戒', job_id=4}, Emp{id=1009, ename='罗贯中', job_id=1}, Emp{id=1010, ename='吴用', job_id=3}, Emp{id=1011, ename='沙僧', job_id=4}, Emp{id=1012, ename='李逵', job_id=4}, Emp{id=1013, ename='小白龙', job_id=4}, Emp{id=1014, ename='关羽', job_id=4}]