概念:JAVA DataBase Connectivity -java 数据库链接,java语言操做数据库java
JDBC本质:sun公司定义的一套JAVA链接各类关系型数据库的规则(接口),并无进行实现,而是由每一个数据库厂商实现了这个接口,而且提供数据库驱动jar包。咱们可使用这套接口(JDBC)编程,真正执行代码的是驱动jar包中的实现类。mysql
JDBC 快速入门spring
package cn.learn.jdbc; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; public class JdbcDemo01 { public static void main(String[] args) { //1.导入厂商jar包,复制包到新建文件夹lib,再add as Library /* mysql厂商的jar包在5版本后里的META-INF中已经注册驱动,可 以不写 Class.forName("com.mysql.jdbc.Driver"); */ Statement statement = null; Connection conn = null; try { //2.注册驱动,加载进内存 Class.forName("com.mysql.jdbc.Driver"); //3.获取数据库链接对象 conn = DriverManager.getConnection("jdbc:mysql:// localhost:3306/db1","root","123"); //4.定义SQL语句,语句不加分号 String sql = " insert into student(id,name) values (8,'小白白') "; //5.获取执行sql的对象,Statement statement = conn.createStatement(); //6.执行SQL int count = statement.executeUpdate(sql); //7.处理结果, if(count == 1){ System.out.println("处理成功"); } } catch (SQLException | ClassNotFoundException e) { e.printStackTrace(); }finally { //8.释放资源,若是在第5步以前出现异常,执行进来statement 为空,则会出现空指针异常 if (statement != null) { try { statement.close(); } catch (SQLException e) { e.printStackTrace(); } } if(conn != null){ try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } } }
java.sql 接口 Connectionsql
开启事务方法:
void setAutoCommit(boolean autoCommit)
将此链接的自动提交模式设置为给定状态,参数false即为手动提交,开启事务数据库
提交事务:void commit()编程
回滚事务:void rollback()安全
java.sql 类 DriverManagerapp
方法:框架
static void registerDriver(Driver driver) 向 DriverManager 注册给定驱动程序dom
而Class.forName("com.mysql.jdbc.Driver");
经过查看源码,在com.mysql.jdbc.Driver类中存在静态代码块
public class Driver extends NonRegisteringDriver implements java.sql.Driver { // // Register ourselves with the DriverManager // static { try { java.sql.DriverManager.registerDriver(new Driver()); } catch (SQLException E) { throw new RuntimeException("Can't register driver!"); } }
静态方法:
static Connection getConnection(String url,String user,String password) 试图创建到给定数据库 URL 的链接。
用于执行静态 SQL 语句并返回它所生成结果的对象。
package cn.learn.jdbc; import java.sql.*; public class JdbcDemo01 { public static void main(String[] args) { //1.导入厂商jar包,复制包到新建文件夹lib,再add as Library /* mysql厂商的jar包在5版本后里的META-INF中已经注册驱动,可 以不写 Class.forName("com.mysql.jdbc.Driver"); */ Statement statement = null; Connection conn = null; ResultSet count = null; try { //2.注册驱动,加载进内存 Class.forName("com.mysql.jdbc.Driver"); //3.获取数据库链接对象 conn = DriverManager.getConnection("jdbc:mysql:/// db1","root","123"); //4.定义SQL语句,语句不加分号 String sql = " select * from student "; //5.获取执行sql的对象,Statement statement = conn.createStatement(); //6.执行SQL count = statement.executeQuery(sql); //7.处理结果,打印在控制台 //7.1 先让光标移动一行,进入数据区域 while(count.next()){ System.out.print(count.getInt(1)+"-----"); System.out.print(count.getString(2)+"-----"); System.out.print(count.getInt(3)+"-----"); System.out.print(count.getDouble(4)+"-----"); System.out.println(count.getDate(5)); } } catch (SQLException | ClassNotFoundException e) { e.printStackTrace(); }finally { //8.释放资源,若是在第5步以前出现异常,执行进来statement 为空,则会出现空指针异常 if (statement != null) { try { statement.close(); } catch (SQLException e) { e.printStackTrace(); } } if(conn != null){ try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } if(count != null){ try { count.close(); } catch (SQLException e) { e.printStackTrace(); } } } } } /* 1-----小白-----15-----85.6-----1996-02-03 2-----小王-----13-----88.2-----null 3-----as-----88-----89.2-----null 8-----小白白-----0-----0.0-----null 9-----小白-----15-----75.6-----1996-02-03 */
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"); String path = res.getPath(); System.out.println(path); pro.load(new FileReader(path)); //3. 获取数据,赋值 url = pro.getProperty("url"); user = pro.getProperty("user"); password = pro.getProperty("password"); driver = pro.getProperty("driver"); //4. 注册驱动 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 stmt * @param conn */ 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(); } } } /** * 释放资源 * @param stmt * @param 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(); } } } }
CREATE TABLE USER( id INT PRIMARY KEY AUTO_INCREMENT, username VARCHAR(32), PASSWORD VARCHAR(32) ); INSERT INTO USER VALUES(NULL,'zhangsan','123'); INSERT INTO USER VALUES(NULL,'lisi','234');
public class JDBCDemo9 { public static void main(String[] args) { //1.键盘录入,接受用户名和密码 Scanner sc = new Scanner(System.in); System.out.println("请输入用户名:"); String username = sc.nextLine(); System.out.println("请输入密码:"); String password = sc.nextLine(); //2.调用方法 boolean flag = new JDBCDemo9().login(username, password); //3.判断结果,输出不一样语句 if(flag){ //登陆成功 System.out.println("登陆成功!"); }else{ System.out.println("用户名或密码错误!"); } } /** * 登陆方法 */ public boolean login(String username ,String password){ if(username == null || password == null){ return false; } //链接数据库判断是否登陆成功 Connection conn = null; prepareStatement pstmt = null; ResultSet rs = null; //1.获取链接 try { conn = JDBCUtils.getConnection(); //2.定义sql String sql = "select * from user where username = ? and password = ?"; //3.获取执行sql的对象 pstmt = conn.prepareStatement(sql); //设置通配符传给须要的对象 pstmt.setString(1,username); pstmt.setString(2,password); //4.执行查询,不须要传参 rs = pstmt.executeQuery(); //5.判断 /* if(rs.next()){//若是有下一行,则返回true return true; }else{ return false; }*/ return rs.next();//若是有下一行,则返回true } catch (SQLException e) { e.printStackTrace(); }finally { JDBCUtils.close(rs,pstmt,conn); } return false; } }
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(); 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); } } }
CREATE DATABASE students; CREATE TABLE scores( id INT PRIMARY KEY, NAME VARCHAR(32) NOT NULL, sex VARCHAR(1), score DOUBLE(5,2) ); INSERT INTO scores VALUES(201826501,'老王','男',88.2),(201826502,'老胡','男',99.3),(201826503,'老薛','男',100),(201826504,'老巴','女',89.3),(201826505,'老谢','女',95.6); UPDATE scores SET score = score-5 WHERE sex='男'; SELECT * FROM scores WHERE id = 201826501;
package cn.work.demo.Jdbc; import java.sql.*; public class JdbcDemo01 { public static void main(String[] args) { //导入厂商jar包,复制包到新建文件夹lib,再add as Library /* mysql厂商的jar包在5版本后里的META-INF中已经注册驱动,能够不写 Class.forName("com.mysql.jdbc.Driver"); */ Connection conn = null; //获取数据库链接对象 try { conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/students", "root", "123"); } catch (SQLException e) { e.printStackTrace(); } //查询所有 Query query = new Query(conn); //修改分数 UpdateScores update = new UpdateScores(conn); //查询单一人员信息 QueryOne onePerson = new QueryOne(conn); //主菜单 Menu menu = new Menu(query,update,onePerson); //关闭链接 try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } }
package cn.work.demo.Jdbc; import java.util.Scanner; public class Menu { private boolean flag = true; private Scanner scanner =null; public Menu(Query query, UpdateScores update, QueryOne onePerson) { System.out.println("\n\n\t\t\tJDBC实验\n\n"); System.out.println("* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *" ); System.out.println("\t\t\t\t1.查询所有人员信息\n"); System.out.println("\t\t\t\t2.修改分数男生-5女生+3\n"); System.out.println("\t\t\t\t3.查询某人信息\n"); System.out.println("\t\t\t\t4.退出\n"); System.out.println("* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *" ); scanner = new Scanner(System.in); //菜单 do{ System.out.println("请输入要选择的数字:"); int command = scanner.nextInt(); switch (command){ case 1: query.execute(); break; case 2: update.execute(); break; case 3: onePerson.execute(); break; case 4: flag=false; break; default: System.out.println("输入错误请从新输入"); break; } }while (flag); } }
package cn.work.demo.Jdbc; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class Query { private Statement statement=null; private Connection conn; private ResultSet count=null; public Query( Connection conn) { this.conn = conn; } public void execute() { try { //定义查询SQL语句,语句不加分号 String sql = " select * from scores "; //获取执行sql的对象,Connection里的方法返回Statement statement = conn.createStatement(); //执行SQL,返回ResultSet count = statement.executeQuery(sql); //处理结果,打印在控制台 //先让光标移动一行,进入数据区域进行打印输出 while (count.next()) { System.out.print(count.getInt(1) + "-----"); System.out.print(count.getString(2) + "-----"); System.out.print(count.getString(3) + "-----"); System.out.println(count.getDouble(4)); } } catch (SQLException e) { e.printStackTrace(); } finally { //释放资源 if (statement != null) { try { statement.close(); } catch (SQLException e) { e.printStackTrace(); } } if (count != null) { try { count.close(); } catch (SQLException e) { e.printStackTrace(); } } } } }
package cn.work.demo.Jdbc; import java.sql.Connection; import java.sql.SQLException; import java.sql.Statement; public class UpdateScores { private Statement statement=null; private Connection conn; public UpdateScores(Connection conn) { this.conn = conn; } public void execute() { try { //定义查询SQL语句 String sqlMen = "UPDATE scores SET score = score-5 WHERE sex='男'"; String sqlWonmen = "UPDATE scores SET score = score+3 WHERE sex='女'"; //建立一个 Statement 对象来将 SQL 语句发送到数据库 statement = conn.createStatement(); //执行SQL statement.executeUpdate(sqlMen); statement.executeUpdate(sqlWonmen); } catch (SQLException e) { e.printStackTrace(); } finally { //释放资源 if (statement != null) { try { statement.close(); } catch (SQLException e) { e.printStackTrace(); } } } } }
package cn.work.demo.Jdbc; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Scanner; public class QueryOne { //PreparedStatement动态参数 private PreparedStatement pstatement=null; private Connection conn; private ResultSet count=null; private Scanner scanner; public QueryOne(Connection conn) { scanner = new Scanner(System.in); this.conn = conn; } public void execute() { try { System.out.println("请输入要查询学号:"); int id = Integer.parseInt(scanner.next()); String sql = "SELECT * FROM scores WHERE id = ?"; //获取SQL执行的对象 pstatement = conn.prepareStatement(sql); //传递动态参数 pstatement.setInt(1,id); //执行SQL count = pstatement.executeQuery(); if (count.next()){ System.out.print(count.getInt(1) + "-----"); System.out.print(count.getString(2) + "-----"); System.out.print(count.getString(3) + "-----"); System.out.println(count.getDouble(4)); } else System.out.println("学号未找到!!!"); } catch (SQLException e) { e.printStackTrace(); } finally { //释放资源 if (pstatement != null) { try { pstatement.close(); } catch (SQLException e) { e.printStackTrace(); } } } } }
//1.建立数据库链接池对象,不传参数则使用默认配置 DataSource ds = new ComboPooledDataSource(); //2. 获取链接对象 Connection conn = ds.getConnection();
//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();
```java
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的开发
代码:
import cn.itcast.domain.Emp; import cn.itcast.utils.JDBCUtils; import org.junit.Test; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import java.sql.Date; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import java.util.Map; public class JdbcTemplateDemo2 { //Junit单元测试,可让方法独立执行 //1. 获取JDBCTemplate对象 private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource()); /** * 1. 修改1号数据的 salary 为 10000 */ @Test public void test1(){ //2. 定义sql String sql = "update emp set salary = 10000 where id = 1001"; //3. 执行sql int count = template.update(sql); System.out.println(count); } /** * 2. 添加一条记录 */ @Test public void test2(){ String sql = "insert into emp(id,ename,dept_id) values(?,?,?)"; int count = template.update(sql, 1015, "郭靖", 10); System.out.println(count); } /** * 3.删除刚才添加的记录 */ @Test public void test3(){ String sql = "delete from emp where id = ?"; int count = template.update(sql, 1015); System.out.println(count); } /** * 4.查询id为1001的记录,将其封装为Map集合 * 注意:这个方法查询的结果集长度只能是1 */ @Test public void test4(){ String sql = "select * from emp where id = ? or id = ?"; Map<String, Object> map = template.queryForMap(sql, 1001,1002); System.out.println(map); //{id=1001, ename=孙悟空, job_id=4, mgr=1004, joindate=2000-12-17, salary=10000.00, bonus=null, dept_id=20} } /** * 5. 查询全部记录,将其封装为List */ @Test public void test5(){ String sql = "select * from emp"; List<Map<String, Object>> list = template.queryForList(sql); for (Map<String, Object> stringObjectMap : list) { System.out.println(stringObjectMap); } } /** * 6. 查询全部记录,将其封装为Emp对象的List集合 */ @Test public void test6(){ String sql = "select * from emp"; List<Emp> list = template.query(sql, new RowMapper<Emp>() { @Override public Emp mapRow(ResultSet rs, int i) throws SQLException { Emp emp = new Emp(); 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.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); return emp; } }); for (Emp emp : list) { System.out.println(emp); } } /** * 6. 查询全部记录,将其封装为Emp对象的List集合 */ @Test public void test6_2(){ String sql = "select * from emp"; List<Emp> list = template.query(sql, new BeanPropertyRowMapper<Emp>(Emp.class)); for (Emp emp : list) { System.out.println(emp); } } /** * 7. 查询总记录数 */ @Test public void test7(){ String sql = "select count(id) from emp"; Long total = template.queryForObject(sql, Long.class); System.out.println(total); } }