Java DataBase Connectivity Java 数据库连接, Java语言操作数据库
其实是官方(sun公司)定义的一套操作所有关系型数据库的规则,即接口。各个数据库厂商去实现这套接口,提供数据库驱动jar包。我们可以使用这套接口(JDBC)编程,真正执行的代码是驱动jar包中的实现类。
一、步骤:
导入驱动jar包 mysql-connector-java-5.1.37-bin.jar 1.复制mysql-connector-java-5.1.37-bin.jar到项目的 libs 目录下 2.(IDEA编译器)右键–>Add As Library (千万别忘记了!!!!)注册驱动获取数据库连接对象 Connection定义 sql 语句,例如: "update account set balance = 500 where id = 1"获取执行sql语句的对象 Statement执行sql,接受返回结果处理结果释放资源二、代码实现:
//1. 导入驱动jar包 //2.注册驱动 Class.forName("com.mysql.jdbc.Driver"); //3.获取数据库连接对象 参数(数据库地址,用户名, 密码) Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/myDB", "root", "root"); //4.定义sql语句 String sql = "update account set balance = 500 where id = 1"; //5.获取执行sql的对象 Statement Statement stmt = conn.createStatement(); //6.执行sql int count = stmt.executeUpdate(sql); //7.处理结果 System.out.println(count); //8.释放资源 stmt.close(); conn.close();注意:mysql5 之后的驱动jar包可以省略注册驱动的步骤,但建议还是写上,以免出现不必要的麻烦
ResultSet :结果集对象,封装查询结果
boolean next() : 游标向下移动一行,判断当前行是否是最后一行末尾 (是否有数据),如果是,则返回false,如果不是则返回true。getXxx(参数): 获取数据
Xxx:代表数据类型 如: int getInt() , String getString()参数: int:代表列的编号,从1开始 如: getString(1)String:代表列名称。 如: getDouble(“balance”)注意:
使用步骤: 1. 游标向下移动一行 2. 判断是否有数据 3. 获取数据 //循环判断游标是否是最后一行末尾。 while(rs.next()){ //获取数据 //6.2 获取数据 int id = rs.getInt(1); String name = rs.getString("name"); double balance = rs.getDouble(3); System.out.println(id + "---" + name + "---" + balance); } 练习: 定义一个方法,查询emp表的数据将其封装为对象,然后装载集合,返回。 定义Emp类定义方法 public List findAll(){}实现方法 select * from emp;代码实现:
定义 javaBean类: package domain; public class Emp { private int id; private String empName; private String salery; private int deptId; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getEmpName() { return empName; } public void setEmpName(String empName) { this.empName = empName; } public String getSalery() { return salery; } public void setSalery(String salery) { this.salery = salery; } public int getDeptId() { return deptId; } public void setDeptId(int deptId) { this.deptId = deptId; } @Override public String toString() { return "Emp{" + "id=" + id + ", empName='" + empName + '\'' + ", salery='" + salery + '\'' + ", deptId=" + deptId + '}'; } } 测试类: package day01.jdbc; import domain.Emp; import java.sql.*; import java.util.ArrayList; import java.util.List; public class JdbcDemo04 { public static void main(String[] args) { List<Emp> list= new JdbcDemo04().findAll(); for (Emp emp : list) { System.out.println(emp); } } public List<Emp> findAll() { Connection conn = null; Statement sta = null; ResultSet res = null; List<Emp> list = null; try { Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection("jdbc:mysql:///dt55?characterEncoding=utf8","root","xxwroot"); String sql = "select * from emp"; sta = conn.createStatement(); res = sta.executeQuery(sql); //6.遍历结果集,封装对象,装载集合 Emp emp = null; list = new ArrayList<Emp>(); while (res.next()) { int id = res.getInt(1); String empName = res.getString("empName"); String salery = res.getString("salery"); int deptId = res.getInt(4); emp = new Emp(); emp.setId(id); emp.setEmpName(empName); emp.setSalery(salery); emp.setDeptId(deptId); list.add(emp); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } finally { if (res != null){ try { res.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } if (sta != null){ try { sta.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } if (conn != null) { try { conn.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } } return list; } }PreparedStatement:执行sql的对象
SQL注入问题:在拼接sql时,有一些sql的特殊关键字参与字符串的拼接。会造成安全性问题。
例子:
输入用户随便,输入密码:a’ or ‘a’ = 'asql:select * from user where username = ‘fhdsjkf’ and password = ‘a’ or ‘a’ = ‘a’ 解决sql注入问题:使用 PreparedStatement 对象来解决预编译的SQL:参数使用 ? 作为占位符步骤: 1. 导入驱动jar包 mysql-connector-java-5.1.37-bin.jar 2. 注册驱动 3. 获取数据库连接对象 Connection 4. 定义sql注意:sql的参数使用?作为占位符。 如:select * from user where username = ? and password = ?;
获取执行sql语句的对象 PreparedStatement Connection.prepareStatement(String sql)给 ?赋值: 方法: setXxx(参数1,参数2) 参数1:?的位置编号 从 1 开始参数2:?的值 执行sql,接受返回结果,不需要传递sql语句处理结果释放资源目的: 简化书写
分析:
注册驱动也抽取抽取一个方法获取连接对象需求:不想传递参数(麻烦),还得保证工具类的通用性。 解决:配置文件jdbc.properties url= user= password=3. 抽取一个方法释放资源
package day01.util.jdbcUtil; import java.io.FileReader; import java.io.IOException; import java.net.URL; import java.sql.*; import java.util.Properties; 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(); //获取src路径下的文件的方式--->ClassLoader 类加载器 ClassLoader classLoader = JDBCUtils.class.getClassLoader(); URL res = classLoader.getResource("jdbc.properties"); // 可以简写成 getResourceAsStream() String path = res.getPath(); pro.load(new FileReader(path)); url = pro.getProperty("url"); user = pro.getProperty("user"); password = pro.getProperty("password"); driver = pro.getProperty("driver"); // 注册驱动 Class.forName(driver); }catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e){ e.printStackTrace(); } } /** * 获取链接 * @return 连接对象 **/ public static Connection getConnection() throws SQLException { return DriverManager.getConnection(url,user,password); } /** * 释放资源 * @param res * @param stmt * @param conn * */ public static void close(ResultSet res ,Statement stmt,Connection conn) { if (res !=null){ try { res.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } if (stmt != null){ try { stmt.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } if (conn != null){ try { conn.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } } }关于 ClassLoader 的深入理解请跳转至: 深入理解ClassLoader工作机制(jdk1.8)
事务:一个包含多个步骤的业务操作。如果这个业务操作被事务管理,则这多个步骤要么同时成功,要么同时失败。
操作:
开启事务 setAutoCommit提交事务 commit回滚事务 rollback使用Connection对象来管理事务
开启事务:setAutoCommit (boolean autoCommit) :调用该方法设置参数为 false,即开启事务 在执行sql之前开启事务 提交事务:commit() 当所有sql都执行完提交事务 回滚事务:rollback() 在 catch 中回滚事务代码:
package day01.jdbc; import day01.util.JDBCUtils; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; /** * 事务操作 */ public class JDBCDemo10 { public static void main(String[] args) { Connection conn = null; PreparedStatement pstmt1 = null; PreparedStatement pstmt2 = null; try { //1.获取连接 conn = JDBCUtils.getConnection(); //开启事务 conn.setAutoCommit(false); //2.定义sql //2.1 张三 - 500 String sql1 = "update account set balance = balance - ? where id = ?"; //2.2 李四 + 500 String sql2 = "update account set balance = balance + ? where id = ?"; //3.获取执行sql对象 pstmt1 = conn.prepareStatement(sql1); pstmt2 = conn.prepareStatement(sql2); //4. 设置参数 pstmt1.setDouble(1,500); pstmt1.setInt(2,1); pstmt2.setDouble(1,500); pstmt2.setInt(2,2); //5.执行sql pstmt1.executeUpdate(); // 手动制造异常 int i = 3/0; pstmt2.executeUpdate(); //提交事务 conn.commit(); } catch (Exception e) { //事务回滚 try { if(conn != null) { conn.rollback(); } } catch (SQLException e1) { e1.printStackTrace(); } e.printStackTrace(); }finally { JDBCUtils.close(pstmt1,conn); JDBCUtils.close(pstmt2,null); } } }
其实就是一个容器(集合),存放数据库连接的容器。当系统初始化好后,容器被创建,容器中会申请一些连接对象,当用户来访问数据库时,从容器中获取连接对象,用户访问完之后,会将连接对象归还给容器。(类似于线程池,用完归还)
标准接口:DataSource javax.sql 包下的 方法:
获取连接:getConnection()归还连接:Connection.close() , 如果连接对象Connection是从连接池中获取的,那么调用 Connection.close() 方法,则不会再关闭连接了,而是归还连接。一般我们不去实现它,有数据库厂商来实现 1. C3P0:数据库连接池技术 2. Druid:数据库连接池实现技术,由阿里巴巴提供的
5. Druid:数据库连接池实现技术,由阿里巴巴提供
1. 步骤:
导入jar包 druid-1.0.9.jar定义配置文件: 是properties形式的可以叫任意名称,可以放在任意目录下 加载配置文件。Properties获取数据库连接池对象:通过工厂来来获取 DruidDataSourceFactory获取连接:getConnection2. 代码:
//3.加载配置文件 Properties pro = new Properties(); InputStream is = DruidDemo.class.getClassLoader().getResourceAsStream("druid.properties"); pro.load(is); //4.获取连接池对象 DataSource ds = DruidDataSourceFactory.createDataSource(pro); //5.获取连接 Connection conn = ds.getConnection();3. 定义工具类:
定义一个类 JDBCUtils提供静态代码块加载配置文件,初始化连接池对象提供方法 获取连接方法:通过数据库连接池获取连接释放资源获取连接池的方法 import com.alibaba.druid.pool.DruidDataSourceFactory; import javax.sql.DataSource; import java.io.IOException; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Properties; /** * Druid连接池的工具类 */ public class JDBCUtils { //1.定义成员变量 DataSource private static DataSource ds ; static{ try { //1.加载配置文件 Properties pro = new Properties(); pro.load(JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties")); //2.获取DataSource ds = DruidDataSourceFactory.createDataSource(pro); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } /** * 获取连接 */ public static Connection getConnection() throws SQLException { return ds.getConnection(); } /** * 释放资源 */ public static void close(Statement stmt,Connection conn){ if(stmt != null){ try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); } } if(conn != null){ try { conn.close();//归还连接 } catch (SQLException e) { e.printStackTrace(); } } close(null,stmt,conn); } public static void close(ResultSet rs , Statement stmt, Connection conn){ if(rs != null){ try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } if(stmt != null){ try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); } } if(conn != null){ try { conn.close();//归还连接 } catch (SQLException e) { e.printStackTrace(); } } } /** * 获取连接池方法 */ public static DataSource getDataSource(){ return ds; } }Spring框架对JDBC的简单封装。提供了一个JDBCTemplate对象简化JDBC的开发
步骤:
导入jar包创建 JdbcTemplate 对象。依赖于数据源 DataSource JdbcTemplate template = new JdbcTemplate(ds); 调用 JdbcTemplate 的方法来完成CRUD的操作 update() : 执行DML语句,增、删、改语句 queryForMap() : 查询结果将结果集封装为map集合,将列名作为key,将值作为value 将这条记录封装为一个map集合注意:这个方法查询的结果集长度只能是1
queryForList() :查询结果将结果集封装为list集合注意:将每一条记录封装为一个Map集合,再将Map集合装载到List集合中
query() : 查询结果,将结果封装为JavaBean对象 query 的参数:RowMapper 一般我们使用 BeanPropertyRowMapper 实现类。可以完成数据到 JavaBean 的自动封装new BeanPropertyRowMapper <类型> (类型.class) queryForObject:查询结果,将结果封装为对象 一般用于聚合函数的查询