概念:Java DataBase Connectivity,Java数据库连接,Java语言操作
本质:是官方(sun公司)定义的一套操作所有关系型数据库的规则,即接口。各个数据库厂商去实现这个接口,提供数据库驱动jar包。我们可以使用这套接口(JDBC)编程,真正执行的代码是驱动jar包中的实现类
步骤:
快速入门
package cn.chao.web; import java.sql.Connection; import java.sql.DriverManager; import java.sql.Statement; public class jdbcDemo1 { public static void main(String[] args) throws Exception{ //1.导入驱动jar包 //2.注册驱动 Class.forName("com.mysql.jdbc.Driver"); //3.获取数据库连接对象 Connection connection= DriverManager.getConnection("jdbc:mysql://localhost:3306/db1","root","password"); //4.定义sql语句 String sql="update emp set job_id = 1 where id = 100"; //5.获取执行sql的对象Statement Statement stmt =connection.createStatement(); //6.执行sql int count=stmt.executeUpdate(sql); //7.处理结果 System.out.println(count); //8.释放资源 stmt.close(); connection.close(); } }
DriverManager:驱动管理对象
static void registerDriver(Driver driver)
:注册与给定的驱动程序DriverManagerClass.forName("com.sql.jdbc.Driver");
static Connection getConnection(String url,String user,String password)
jdbc:mysql://ip地址(域名):端口号/数据库名称
jdbc:mysql:///数据库名称
Connection:数据库连接对象
Statement createStatement()
PreparedStatement prepareStatement(String sql)
setAutoCommit(boolean autoCommit)
:调用该方法设置参数为false,即开启事务commit()
rollback()
Statement:执行sql的对象
boolean execute(String sql)
:可以执行任意的sqlint executeUpdate(String sql)
:执行DML(insert、update、delete)语句、DDL(create、alter、drop)语句,返回值是影响的行数ResultSet executeQuery(String sql)
:执行DQL(select)语句ResultSet:结果集对象
next()
:游标向下移动一行getXxx(参数)
:获取数据
int getInt()
,String getString()
int
:代表列的编号,从1开始 ,如:getString(1)
String
:代表列名称,如:getDouble("name")
PreparedStatement:执行sql的对象
a' or 'a' = 'a
select * from user where username='assdf' and password= 'a' or 'a' ='a'
PreparedStatement Connection.prepareStatement(String sql)
setXxx(参数1,参数2)
,package cn.chao.web; import sun.tracing.dtrace.DTraceProviderFactory; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; //insert练习 public class jdbcDemo2 { public static void main(String[] args) { Statement stmt=null; Connection connection=null; try{ //1.注册驱动 Class.forName("com.mysql.jdbc.Driver"); //2.定义sql String sql="insert into dept values(50,'硬件部','长沙')"; //3.获取Connection对象 connection= DriverManager.getConnection("jdbc:mysql:///db1","root","root"); //4.获取执行sql的对象statement stmt=connection.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 e){ e.printStackTrace(); }finally { //7.释放资源 //避免空指针异常 if(stmt!=null){ try{ stmt.close(); }catch(SQLException e){ e.printStackTrace(); } } if(connection!=null){ try{ connection.close(); }catch(SQLException e){ e.printStackTrace(); } } } } }
package cn.chao.web; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; //update练习 public class jdbcDemo3 { public static void main(String[] args) { Statement stmt=null; Connection connection=null; try{ //1.注册驱动 Class.forName("com.mysql.jdbc.Driver"); //2.定义sql String sql="update dept set loc = '耒阳' where id = 50"; //3.获取Connection对象 connection= DriverManager.getConnection("jdbc:mysql:///db1","root","root"); //4.获取执行sql的对象statement stmt=connection.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 e){ e.printStackTrace(); }finally { //7.释放资源 //避免空指针异常 if(stmt!=null){ try{ stmt.close(); }catch(SQLException e){ e.printStackTrace(); } } if(connection!=null){ try{ connection.close(); }catch(SQLException e){ e.printStackTrace(); } } } } }
package cn.chao.web; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; //delete练习 public class jdbcDemo4 { public static void main(String[] args) { Statement stmt=null; Connection connection=null; try{ //1.注册驱动 Class.forName("com.mysql.jdbc.Driver"); //2.定义sql String sql="delete from dept where id = 50"; //3.获取Connection对象 connection= DriverManager.getConnection("jdbc:mysql:///db1","root","root"); //4.获取执行sql的对象statement stmt=connection.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 e){ e.printStackTrace(); }finally { //7.释放资源 //避免空指针异常 if(stmt!=null){ try{ stmt.close(); }catch(SQLException e){ e.printStackTrace(); } } if(connection!=null){ try{ connection.close(); }catch(SQLException e){ e.printStackTrace(); } } } } }
package cn.chao.web; import java.sql.*; //获取单行数据练习 public class jdbcDemo5 { public static void main(String[] args) { Statement stmt=null; Connection connection=null; ResultSet rs=null; try{ //1.注册驱动 Class.forName("com.mysql.jdbc.Driver"); //2.定义sql String sql="select * from dept"; //3.获取Connection对象 connection= DriverManager.getConnection("jdbc:mysql:///db1","root","root"); //4.获取执行sql的对象statement stmt=connection.createStatement(); //5.执行sql rs = stmt.executeQuery(sql); //6.处理结果 //6.1 让游标向下移动一行 rs.next(); //6.2 获取数据 int id=rs.getInt(1); String dname=rs.getString("dname"); String loc=rs.getString("loc"); System.out.println(id+"---"+dname+"---"+loc); }catch(ClassNotFoundException e){ e.printStackTrace(); }catch(SQLException e){ e.printStackTrace(); }finally { //7.释放资源 //避免空指针异常 if(rs!=null){ try{ rs.close(); }catch(SQLException e){ e.printStackTrace(); } } if(stmt!=null){ try{ stmt.close(); }catch(SQLException e){ e.printStackTrace(); } } if(connection!=null){ try{ connection.close(); }catch(SQLException e){ e.printStackTrace(); } } } } }
package cn.chao.web; import java.sql.*; //获取多行数据练习 public class jdbcDemo6 { public static void main(String[] args) { Statement stmt=null; Connection connection=null; ResultSet rs=null; try{ //1.注册驱动 Class.forName("com.mysql.jdbc.Driver"); //2.定义sql String sql="select * from dept"; //3.获取Connection对象 connection= DriverManager.getConnection("jdbc:mysql:///db1","root","root"); //4.获取执行sql的对象statement stmt=connection.createStatement(); //5.执行sql rs = stmt.executeQuery(sql); //6.处理结果 while(rs.next()){ //循环判断游标是否是最后一行 int id=rs.getInt(1); String dname=rs.getString("dname"); String loc=rs.getString("loc"); System.out.println(id+"---"+dname+"---"+loc); } }catch(ClassNotFoundException e){ e.printStackTrace(); }catch(SQLException e){ e.printStackTrace(); }finally { //7.释放资源 //避免空指针异常 if(rs!=null){ try{ rs.close(); }catch(SQLException e){ e.printStackTrace(); } } if(stmt!=null){ try{ stmt.close(); }catch(SQLException e){ e.printStackTrace(); } } if(connection!=null){ try{ connection.close(); }catch(SQLException e){ e.printStackTrace(); } } } } }
package domain; import java.util.Date; /* * 封装emp表数据的JavaBean */ public class Emp { private int id; private String ename; private int job_id; private int mgr; private Date joindate; private double salary; private double bonus; private int dept_id; @Override public String toString() { return "Emp{" + "id=" + id + ", ename='" + ename + '\'' + ", job_id=" + job_id + ", mgr=" + mgr + ", joindate=" + joindate + ", salary=" + salary + ", bonus=" + bonus + ", dept_id=" + dept_id + '}'; } public int getId() { return id; } public String getEname() { return ename; } public int getJob_id() { return job_id; } public int getMgr() { return mgr; } public Date getJoindate() { return joindate; } public double getSalary() { return salary; } public double getBonus() { return bonus; } public int getDept_id() { return dept_id; } public void setId(int id) { this.id = id; } public void setEname(String ename) { this.ename = ename; } public void setJob_id(int job_id) { this.job_id = job_id; } public void setMgr(int mgr) { this.mgr = mgr; } public void setJoindate(Date joindate) { this.joindate = joindate; } public void setSalary(double salary) { this.salary = salary; } public void setBonus(double bonus) { this.bonus = bonus; } public void setDept_id(int dept_id) { this.dept_id = dept_id; } }
package cn.chao.web; import domain.Emp; import java.sql.*; import java.util.ArrayList; import java.util.List; public class jdbcDemo7 { /** * 查询所有emp对象 */ public static void main(String[] args) { List<Emp> list=new jdbcDemo7().findAll(); System.out.println(list); } public List<Emp> findAll(){ Statement stmt=null; Connection connection=null; ResultSet rs=null; List<Emp> list=null; try{ //1.注册驱动 Class.forName("com.mysql.jdbc.Driver"); //2.定义sql String sql="select * from emp"; //3.获取Connection对象 connection= DriverManager.getConnection("jdbc:mysql:///db1","root","root"); //4.获取执行sql的对象 stmt=connection.createStatement(); //5.执行sql rs = stmt.executeQuery(sql); //6.遍历结果集,封装对象,装载集合 Emp emp=null; list=new ArrayList<Emp>(); while(rs.next()){ //获取数据 int id=rs.getInt("id"); String ename=rs.getString("ename"); int job_id=rs.getInt("job_id"); int mgr=rs.getInt("mgr"); Date joindate=rs.getDate("joindate"); double salary=rs.getDouble("salary"); double bonus=rs.getDouble("bonus"); int dept_id=rs.getInt("dept_id"); //创建emp对象并赋值 emp=new Emp(); emp.setId(id); emp.setEname(ename); emp.setJob_id(job_id); emp.setMgr(mgr); emp.setJoindate(joindate); emp.setSalary(salary); emp.setBonus(bonus); emp.setDept_id(dept_id); //装载集合 list.add(emp); } }catch(ClassNotFoundException e){ e.printStackTrace(); }catch(SQLException e){ e.printStackTrace(); }finally { //7.释放资源 //避免空指针异常 if(rs!=null){ try{ rs.close(); }catch(SQLException e){ e.printStackTrace(); } } if(stmt!=null){ try{ stmt.close(); }catch(SQLException e){ e.printStackTrace(); } } if(connection!=null){ try{ connection.close(); }catch(SQLException e){ e.printStackTrace(); } } } return list; } }
package cn.chao.web; import utils.JDBCUtils; import java.sql.*; import java.util.Scanner; /** * 登录案例 */ public class jdbcDemo9 { public static void main(String[] args) { Scanner scanner=new Scanner(System.in); System.out.println("请输入用户名:"); String username=scanner.nextLine(); System.out.println("请输入密码:"); String password=scanner.nextLine(); boolean flag=new jdbcDemo9().login2(username,password); if(flag){ System.out.println("登陆成功!"); } else{ System.out.println("登录失败!"); } } /** * 登录方法 */ public boolean login(String username,String password){ if(username==null || password==null){ return false; } Connection connection=null; Statement stmt=null; ResultSet rs=null; try { //获取连接对象 connection= JDBCUtils.getConnection(); //定义sql String sql="select * from user where username='"+username+"' and password='"+password+"'"; //获取执行sql的对象 stmt=connection.createStatement(); //执行查询 rs=stmt.executeQuery(sql); return rs.next(); } catch (SQLException throwables) { throwables.printStackTrace(); } finally { JDBCUtils.close(rs,stmt,connection); } return false; } /** * 优化 */ public boolean login2(String username,String password){ if(username==null || password==null){ return false; } Connection connection=null; PreparedStatement pstmt=null; ResultSet rs=null; try { //获取连接对象 connection= JDBCUtils.getConnection(); //定义sql String sql="select * from user where username= ? and password= ?"; //获取执行sql的对象 pstmt=connection.prepareStatement(sql); //给?赋值 pstmt.setString(1,username); pstmt.setString(2,password); //执行查询 rs=pstmt.executeQuery(); return rs.next(); } catch (SQLException throwables) { throwables.printStackTrace(); } finally { JDBCUtils.close(rs,pstmt,connection); } return false; } }
目的:简化书写
分析:
注册驱动
抽取一个方法获取连接对象
需求:不想传递参数,还得保证工具类的通用性
解决方案:配置文件
抽取一个方法释放资源
案例:
url=jdbc:mysql:///db1 user=root password=root driver=com.mysql.jdbc.Driver
package utils; import java.io.FileReader; import java.io.IOException; import java.net.URL; import java.sql.*; import java.util.Properties; /** * JDBC工具类 */ public class JDBCUtils { //只有静态变量能被静态代码块访问,被静态方法访问 private static String url; private static String user; private static String password; private static String driver; /** * 文件的读取:只需要读取一次即可拿到这些值,使用静态代码块 */ static { try { //读取资源文件,获取值 //1.创建Properties集合类 Properties pro=new Properties(); //2.获取src路径下的文件的方式-->ClassLoader类加载器 ClassLoader classLoader=JDBCUtils.class.getClassLoader(); URL res=classLoader.getResource("jdbc.properties");//获取资源路径的绝对路径 String path =res.getPath(); System.out.println("path:"+path); //3.加载文件 pro.load(new FileReader(path)); //4.获取数据,赋值 url=pro.getProperty("url"); user=pro.getProperty("user"); password=pro.getProperty("password"); driver=pro.getProperty("driver"); //5.注册驱动 Class.forName(driver); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } /** * 获取连接 * 返回连接对象 */ public static Connection getConnection() throws SQLException { return DriverManager.getConnection(url,user,password); } /** * 释放资源 * @param stmt * @param connection */ public static void close(Statement stmt,Connection connection){ if(stmt!=null){ try { stmt.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } if(connection!=null){ try { connection.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } } /** * 释放资源 * @param rs * @param stmt * @param connection */ public static void close(ResultSet rs,Statement stmt, Connection connection){ if(rs!=null){ try { rs.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } if(stmt!=null){ try { stmt.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } if(connection!=null){ try { connection.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } } }
package cn.chao.web; import domain.Emp; import utils.JDBCUtils; import java.sql.*; import java.util.ArrayList; import java.util.List; public class jdbcDemo8 { /** * 使用JDBC工具类简化代码 * 查询所有emp对象 */ public static void main(String[] args) { List<Emp> list=new jdbcDemo8().findAll2(); System.out.println(list); } /** * 演示JDBC工具类 * @return */ public List<Emp> findAll2(){ Statement stmt=null; Connection connection=null; ResultSet rs=null; List<Emp> list=null; try{ connection=JDBCUtils.getConnection(); //定义sql String sql="select * from emp"; //获取执行sql的对象 stmt=connection.createStatement(); //执行sql rs = stmt.executeQuery(sql); //遍历结果集,封装对象,装载集合 Emp emp=null; list=new ArrayList<Emp>(); while(rs.next()){ //获取数据 int id=rs.getInt("id"); String ename=rs.getString("ename"); int job_id=rs.getInt("job_id"); int mgr=rs.getInt("mgr"); Date joindate=rs.getDate("joindate"); double salary=rs.getDouble("salary"); double bonus=rs.getDouble("bonus"); int dept_id=rs.getInt("dept_id"); //创建emp对象并赋值 emp=new Emp(); emp.setId(id); emp.setEname(ename); emp.setJob_id(job_id); emp.setMgr(mgr); emp.setJoindate(joindate); emp.setSalary(salary); emp.setBonus(bonus); emp.setDept_id(dept_id); //装载集合 list.add(emp); } }catch(SQLException e){ e.printStackTrace(); }finally { //7.释放资源 //避免空指针异常 JDBCUtils.close(rs,stmt,connection); } return list; } }
setAutoCommit(boolean autoCommit)
:调用该方法设置参数为false即开启事务
commit()
rollback()
登录案例:
package cn.chao.web; import utils.JDBCUtils; import java.sql.*; import java.util.Scanner; /** * 登录案例 */ public class jdbcDemo10 { public static void main(String[] args) { Connection connection=null; PreparedStatement pstmt1=null; PreparedStatement pstmt2=null; try { //1.获取;连接 connection=JDBCUtils.getConnection(); //开启事务 connection.setAutoCommit(false); //2.定义sql String sql1="update money set balance = balance - ? where id = ?"; String sql2="update money set balance = balance + ? where id = ?"; //3.获取执行sql对象 pstmt1=connection.prepareStatement(sql1); pstmt2=connection.prepareStatement(sql2); //4.设置参数 pstmt1.setInt(1,500); pstmt1.setInt(2,1); pstmt2.setInt(1,500); pstmt2.setInt(2,2); //执行sql pstmt1.executeUpdate(); pstmt2.executeUpdate(); //提交事务 connection.commit(); } catch (Exception throwables) { //回滚事务 try { if(connection!=null){ connection.rollback(); } } catch (SQLException e) { e.printStackTrace(); } throwables.printStackTrace(); } finally { JDBCUtils.close(pstmt1,connection); JDBCUtils.close(pstmt1,null); } } /** * 登录方法 */ public boolean login(String username,String password){ if(username==null || password==null){ return false; } Connection connection=null; Statement stmt=null; ResultSet rs=null; try { //获取连接对象 connection= JDBCUtils.getConnection(); //定义sql String sql="select * from user where username='"+username+"' and password='"+password+"'"; //获取执行sql的对象 stmt=connection.createStatement(); //执行查询 rs=stmt.executeQuery(sql); return rs.next(); } catch (SQLException throwables) { throwables.printStackTrace(); } finally { JDBCUtils.close(rs,stmt,connection); } return false; } /** * 优化 */ public boolean login2(String username,String password){ if(username==null || password==null){ return false; } Connection connection=null; PreparedStatement pstmt=null; ResultSet rs=null; try { //获取连接对象 connection= JDBCUtils.getConnection(); //定义sql String sql="select * from user where username= ? and password= ?"; //获取执行sql的对象 pstmt=connection.prepareStatement(sql); //给?赋值 pstmt.setString(1,username); pstmt.setString(2,password); //执行查询 rs=pstmt.executeQuery(); return rs.next(); } catch (SQLException throwables) { throwables.printStackTrace(); } finally { JDBCUtils.close(rs,pstmt,connection); } return false; } }