15.JDBC (java database connection)

Java数据库连接,(Java Database Connectivity,简称JDBC)是Java语言中用来规范客户端程序如何来访问数据库的应用程序接口,提供了诸如查询和更新数据库中数据的方法。JDBC也是Sun Microsystems的商标。我们通常说的JDBC是面向关系型数据库的。

  • 反射
  • JDBC的驱动jar包 mysql-connector-java.5.1.49.jar

15.1 Connection (数据库的连接)

A connection (session) with a specific
database. SQL statements are executed and results are returned
within the context of a connection.

数据库连接(会话),声明数据库连接的信息。连接获取sql语句的执行statement和返回执行的结果。

JDBCUtil.java

package com.shangguan.jdbc.utils;import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;/*** @ClassName: JDBCUtil* @Description: 数据库连接的工具类* @Author: 一尘* @Date: 2020 年 08 月 26 9:27* @Version 1.0*/
public class JDBCUtil {// 数据库连接的驱动private static String  JDBC_DRIVER = "com.mysql.jdbc.Driver";//数据库的urlprivate static String JDBC_URL = "jdbc:mysql://localhost:3306/hello?useSSL=true";//用户名private static String JDBC_USER = "root";//密码private static String JDBC_PASSWORD = "root";//获取数据库连接的方法public static Connection getConnection(){Connection  connection = null;//我们要通过驱动去连接数据库//获取数据库的驱动try {//加载驱动Class.forName(JDBC_DRIVER);//DriverManagerconnection =  DriverManager.getConnection(JDBC_URL,JDBC_USER,JDBC_PASSWORD);//jdk1.7异常链处理} catch (ClassNotFoundException|SQLException e) {e.printStackTrace();}return connection;}public  static  void close(Connection  con, Statement  statement , ResultSet  resultSet){if(con!=null){try {con.close();con=null;} catch (SQLException e) {e.printStackTrace();}}if(statement!=null){try {statement.close();statement=null;} catch (SQLException e) {e.printStackTrace();}}if(resultSet!=null){try {resultSet.close();resultSet=null;} catch (SQLException e) {e.printStackTrace();}}}}

Book.java

package com.shangguan.jdbc.beans;/*** @ClassName: Book* @Description: book* @Author: 一尘* @Date: 2020 年 08 月 26 9:49* @Version 1.0*/
public class Book {//主键private Integer bookId;private String bookName;private String bookAuthor;private double bookPrice;private String bookPublish;private String bookImg;public Book() {}public Book(String bookName, String bookAuthor, double bookPrice, String bookPublish, String bookImg) {this.bookName = bookName;this.bookAuthor = bookAuthor;this.bookPrice = bookPrice;this.bookPublish = bookPublish;this.bookImg = bookImg;}public Book(Integer bookId, String bookName, String bookAuthor, double bookPrice, String bookPublish, String bookImg) {this.bookId = bookId;this.bookName = bookName;this.bookAuthor = bookAuthor;this.bookPrice = bookPrice;this.bookPublish = bookPublish;this.bookImg = bookImg;}public Integer getBookId() {return bookId;}public void setBookId(Integer bookId) {this.bookId = bookId;}public String getBookName() {return bookName;}public void setBookName(String bookName) {this.bookName = bookName;}public String getBookAuthor() {return bookAuthor;}public void setBookAuthor(String bookAuthor) {this.bookAuthor = bookAuthor;}public double getBookPrice() {return bookPrice;}public void setBookPrice(double bookPrice) {this.bookPrice = bookPrice;}public String getBookPublish() {return bookPublish;}public void setBookPublish(String bookPublish) {this.bookPublish = bookPublish;}public String getBookImg() {return bookImg;}public void setBookImg(String bookImg) {this.bookImg = bookImg;}@Overridepublic String toString() {return "Book{" +"bookId=" + bookId +", bookName='" + bookName + '\'' +", bookAuthor='" + bookAuthor + '\'' +", bookPrice=" + bookPrice +", bookPublish='" + bookPublish + '\'' +", bookImg='" + bookImg + '\'' +'}';}
}

BookDao.java

package com.shangguan.jdbc.dao;import com.shangguan.jdbc.beans.Book;import java.util.List;public interface BookDao {//查询所有数据List<Book> queryAll();//根据id查询Book queryById(int bookId);//模糊查询List<Book> queryLikeBookName(String bookName);//添加数据int addBook(Book book);//修改数据int updateBook(Book book);//删除数据int deleteBook(Book book);
}

15.2 Statement

The object used for executing a static SQL statement
and returning the results it produces.

执行静态的Sql语句对象返回结果.静态sql就是定义死的Sql语句。

  • execute()执行sql语句。

15.3 ResultSet

A table of data representing a database result set, which is usually generated by executing a statement that queries the database.

返回数据库的结果集对象。

package com.shangguan.jdbc.impl;import com.shangguan.jdbc.beans.Book;
import com.shangguan.jdbc.dao.BookDao;
import com.shangguan.jdbc.utils.JDBCUtil;import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;/*** @ClassName: BookDaoImpl* @Description:* @Author: 一尘* @Date: 2020 年 08 月 26 9:56* @Version 1.0*/
public class BookDaoImpl implements BookDao {//获取到数据库的连接Connection  connection = JDBCUtil.getConnection();Statement  statement = null;ResultSet  resultSet = null;@Overridepublic List<Book> queryAll() {List<Book> list = new ArrayList<>();String  sql = "select * from book";try {statement =   connection.createStatement();resultSet = statement.executeQuery(sql);//遍历结果集while(resultSet.next()){Book book = new Book();book.setBookId(resultSet.getInt(1));book.setBookName(resultSet.getString(2));book.setBookAuthor(resultSet.getString(3));book.setBookPrice(resultSet.getDouble(4));book.setBookPublish(resultSet.getString(5));book.setBookImg(resultSet.getString(6));list.add(book);}} catch (SQLException e) {e.printStackTrace();}return list;}@Overridepublic Book queryById(int bookId) {Book  book = null;String sql = "select * from book where bookid = 2 ";try {statement =   connection.createStatement();resultSet = statement.executeQuery(sql);if(resultSet.next()){book = new Book();book.setBookId(resultSet.getInt("bookid"));book.setBookName(resultSet.getString("bookname"));book.setBookAuthor(resultSet.getString("bookauthor"));book.setBookPrice(resultSet.getDouble("bookprice"));book.setBookPublish(resultSet.getString("bookpublish"));book.setBookImg(resultSet.getString("bookimg"));}} catch (SQLException e) {e.printStackTrace();}return book;}@Overridepublic List<Book> queryLikeBookName(String bookName) {List<Book> list = new ArrayList<>();String sql = "select * from book where bookname like concat('%','水浒','%')";try {statement = connection.createStatement();ResultSet resultSet = statement.executeQuery(sql);//遍历结果集while(resultSet.next()){Book book = new Book();book.setBookId(resultSet.getInt(1));book.setBookName(resultSet.getString(2));book.setBookAuthor(resultSet.getString(3));book.setBookPrice(resultSet.getDouble(4));book.setBookPublish(resultSet.getString(5));book.setBookImg(resultSet.getString(6));list.add(book);}} catch (SQLException e) {e.printStackTrace();}return list;}@Overridepublic int addBook(Book book) {int result = 0;String sql = "insert into book values(null,'围城','钱钟书',99.99,'人民出版社','images/1.png')" ;try {statement =  connection.createStatement();result = statement.executeUpdate(sql);} catch (SQLException e) {e.printStackTrace();}return result;}@Overridepublic int updateBook(Book book) {int result = 0;String sql = "update book set bookname = '骆驼祥子',bookauthor='老舍',bookprice=120.00,bookpublish='工业出版社',bookimg='images/2.png' where bookid = 126  ";try {statement =  connection.createStatement();result = statement.executeUpdate(sql);} catch (SQLException e) {e.printStackTrace();}return result;}@Overridepublic int deleteBook(Book book) {int result = 0;String sql = "delete from book where bookid = 126";try {statement = connection.createStatement();result = statement.executeUpdate(sql);} catch (SQLException e) {e.printStackTrace();}return result;}
}

我们发现一些问题:

  • 我们使用的是statement 所以sql语句是静态sql ,数据必须写死 不灵活
  • 在resultset中封装数据存在大量重复的代码。在原生的jdbc中必须这样做
  • 封装好的JDBC库,DBUtils

15.4 PreparedStatement(预编译的SQl)

  • 使用?先进行占位

  • 在根据参数的数据类型调用对应的方法设置参数的实际值到参数对应的占位符所在的位置。

  • 参数的下标是从1开始。

package com.shangguan.jdbc.impl;import com.shangguan.jdbc.beans.Book;
import com.shangguan.jdbc.dao.BookDao;
import com.shangguan.jdbc.utils.JDBCUtil;import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;/*** @ClassName: BookDaoImpl2* @Description:* @Author: 一尘* @Date: 2020 年 08 月 26 10:53* @Version 1.0*/
public class BookDaoImpl2 implements BookDao {Connection  connection = JDBCUtil.getConnection();//预编译的SqlPreparedStatement  preparedStatement = null;ResultSet  resultSet = null;@Overridepublic List<Book> queryAll() {List<Book>     list = new ArrayList<>();String sql = "select * from book";try {preparedStatement =   connection.prepareStatement(sql);resultSet =   preparedStatement.executeQuery();while(resultSet.next()){Book     book = new Book();book.setBookId(resultSet.getInt("bookid"));book.setBookName(resultSet.getString("bookname"));book.setBookAuthor(resultSet.getString("bookauthor"));book.setBookPrice(resultSet.getDouble("bookprice"));book.setBookPublish(resultSet.getString("bookpublish"));book.setBookImg(resultSet.getString("bookimg"));list.add(book);}} catch (SQLException e) {e.printStackTrace();}return list;}@Overridepublic Book queryById(int bookId) {Book book = null;//?就是占位符String sql = "select * from book where bookid = ?";try {preparedStatement =     connection.prepareStatement(sql);//将实际的参数设置到坑位上preparedStatement.setInt(1,bookId);resultSet =  preparedStatement.executeQuery();if(resultSet.next()){book = new Book();book.setBookId(resultSet.getInt("bookid"));book.setBookName(resultSet.getString("bookname"));book.setBookAuthor(resultSet.getString("bookauthor"));book.setBookPrice(resultSet.getDouble("bookprice"));book.setBookPublish(resultSet.getString("bookpublish"));book.setBookImg(resultSet.getString("bookimg"));}} catch (SQLException e) {e.printStackTrace();}return book;}@Overridepublic List<Book> queryLikeBookName(String bookName) {List<Book> list = new ArrayList<>();String sql = "select * from book where bookname like concat('%',?,'%')";try {preparedStatement = connection.prepareStatement(sql);preparedStatement.setString(1,bookName);resultSet = preparedStatement.executeQuery();while(resultSet.next()){Book     book = new Book();book.setBookId(resultSet.getInt("bookid"));book.setBookName(resultSet.getString("bookname"));book.setBookAuthor(resultSet.getString("bookauthor"));book.setBookPrice(resultSet.getDouble("bookprice"));book.setBookPublish(resultSet.getString("bookpublish"));book.setBookImg(resultSet.getString("bookimg"));list.add(book);}} catch (SQLException e) {e.printStackTrace();}return list;}@Overridepublic int addBook(Book book) {int  result = 0;String sql = "insert into book values(null,?,?,?,?,?)";try {preparedStatement  = connection.prepareStatement(sql);preparedStatement.setString(1,book.getBookName());preparedStatement.setString(2,book.getBookAuthor());preparedStatement.setDouble(3,book.getBookPrice());preparedStatement.setString(4,book.getBookPublish());preparedStatement.setString(5,book.getBookImg());result  = preparedStatement.executeUpdate();} catch (SQLException e) {e.printStackTrace();}return result;}@Overridepublic int updateBook(Book book) {int result = 0;String sql = "update book set bookname = ?,bookauthor=?,bookprice = ?,bookpublish = ?,bookimg = ? where bookid =  ?";try {preparedStatement  = connection.prepareStatement(sql);preparedStatement.setString(1,book.getBookName());preparedStatement.setString(2,book.getBookAuthor());preparedStatement.setDouble(3,book.getBookPrice());preparedStatement.setString(4,book.getBookPublish());preparedStatement.setString(5,book.getBookImg());preparedStatement.setInt(6,book.getBookId());result = preparedStatement.executeUpdate();} catch (SQLException e) {e.printStackTrace();}return result;}@Overridepublic int deleteBook(Book book) {int result = 0;String sql = "delete from book where bookid = ?";try {preparedStatement = connection.prepareStatement(sql);preparedStatement.setInt(1,book.getBookId());result = preparedStatement.executeUpdate();} catch (SQLException e) {e.printStackTrace();}return result;}
}

15.5 单元测试(JUNIT)

  • junit 最低是4.12
  • 需要junit的依赖包
    • harmcrest-core
package com.shangguan.jdbc.test;import com.shangguan.jdbc.beans.Book;import com.shangguan.jdbc.dao.BookDao;import com.shangguan.jdbc.impl.BookDaoImpl2;import org.junit.Test;import java.util.List;/*** @ClassName: BookTest2* @Description:* @Author: 一尘* @Date: 2020 年 08 月 26 10:57* @Version 1.0*/
public class BookTest2 {BookDao  bookDao = new BookDaoImpl2();@Testpublic  void queryAll(){List<Book> books = bookDao.queryAll();for (Book book : books) {System.out.println(book);}}@Testpublic  void queryById(){System.out.println(bookDao.queryById(11));}@Testpublic  void queryLikeName(){List<Book> list = bookDao.queryLikeBookName("水浒");for (Book book : list) {System.out.println(book);}}@Testpublic  void addBook(){Book book = new Book("被窝是青春的坟墓","七堇年",99.99,"文艺出版社","images/3.jpg");System.out.println(bookDao.addBook(book));}@Testpublic  void updateBook(){Book book = new Book(127,"灯下尘","七堇年",99.99,"文艺出版社","images/3.jpg");System.out.println(bookDao.updateBook(book));}@Testpublic  void deleteBook(){Book book = new Book();book.setBookId(127);System.out.println(bookDao.deleteBook(book));}
}

接口实现类完成以后,里面所有的方法必须先经过单元测试,测试方法的完整性,再在后续的程序中进行调用。

数据库MySQL(基础六)相关推荐

  1. 麦子mysql_[数据库]MySQL基础 (麦子学员 php 第二阶段)

    [数据库]MySQL基础 (麦子学员 php 第二阶段) 0 2018-08-13 03:00:11 通过my.ini配置文件修改字符集:客户端字符集设置:[mysql]default-charact ...

  2. mysql以下日期函数正确的_[数据库]MYSQL基础03(日期函数)

    [数据库]MYSQL基础03(日期函数) 0 2015-10-29 01:00:09 工作中对日期的处理是经常遇到的,需求可能多种多样,因此重点介绍. 1.获取当前日期select NOW()-- 结 ...

  3. 【MySQL】黑马教程MySQL数据库 MySQL基础(一)

    文章目录 [MySQL]黑马教程MySQL数据库 | MySQL基础(一) MySQL启动 MySQL客户端连接 MySQL数据模型 SQL SQL分类 DDL 表操作-查询 表操作-创建 表操作-数 ...

  4. 数据库-MySQL(六)

    文章目录 一 . 数据库介绍 1.1 什么是数据库 1.2 作用 二 .数据库安装和配置 2.1 压缩式安装 2.2 普通安装 2.3 数据库登录 三 .SQL语句 3.1 SQL语句概述 3.2 S ...

  5. 数据库MySQL基础---DDL/DML/DQL

    MySQL基础 数据库简介 数据库是"按照数据结构来组织.存储和管理数据的仓库".是一个长期存储在计算机内的.有组织的.可共享的.统一管理的大量数据的集合. 与数据库相关的概念数据 ...

  6. 数据库Mysql基础------第一部分 数据的准备与基础命令

    一.初识数据库 一.为什么要用数据库? 数据库(Database)是按照数据结构来组织.存储和管理数据的仓库 数据库随时随地的存在,并且使用,简单的说,数据库就是收集数据的结构.数据涉及很多,例如一个 ...

  7. Mac安装mysql数据库MySQL基础和MySQL在开发中常用的技术

    一.安装步骤 打开终端,输入: sudo vi ~/.bash_profile 输入 i 然后粘贴以下内容 # mysql alias mysql='/usr/local/mysql/bin/mysq ...

  8. [数据库] MySQL基础知识之日期判断及添加排序序号

    这篇文章主要记录MySQL中遇到的几个基础问题,希望文章对你有所帮助!包括:         1.日期类型的判断         2.decode函数的替代方法         3.查询语句中添加一个 ...

  9. mysql 同一张表 某个字段更新到另一条数据上_面试基础:数据库MySQL基础入门(下)...

    本文是面试基础的第二篇.本篇偏理论,包括三节: 事务和并发 数据库设计 索引 所选的三个内容均是面试的高频考察点,需要细致地理解 No.1     事务和并发 事务:数据库操作的基本单元.对于数据库的 ...

  10. mysql 删除时间一个星期_15天快速学习 数据库Mysql 基础操作命令(第一章)

    简言 你还在为不了解不会操作MySQL数据库而苦恼吗? 还为面对冗繁的数据不知怎么提取而愤懑吗? 分享快速学习MySQL及基础操作命令 那就利用闲暇时间和我一起掌握一门MySQL数据库语言操作吧! 入 ...

最新文章

  1. springboot默认开启事务吗_香~Spring Boot 应用也可以有配置中心。
  2. Java 23种设计模式案例:原则及分类
  3. python无法导入numpy_python – Pycharm无法导入numpy
  4. plsql存过声明游标_plsql--游标用法
  5. Confluence 6 创建一个用户宏
  6. MySQL DEBUG_SYNC 的简单分析与测试
  7. Dirichlet energy and the Laplace equation
  8. 智能实验室-全能优化(Guardio) 4.94.0.830
  9. GitHub - ErnestChen1/SmartSpeaker: 一个基于云端语音识别的智能控制设备,类似于天猫精灵,小爱同学。采用的芯片为stm32f407,wm8978,esp8266。...
  10. MyEclipse10安装properties文件插件
  11. mqtt测试工具(持续更新...)
  12. 抓取沪A股票资金流向数据
  13. TextView 设置显示省略号
  14. SpringMv的IOC控制反转以及DI依赖注入(SpringMvc⑨)
  15. 王小锤学Java:retainAll函数那点儿事
  16. CryptoNight
  17. 电脑窗口全半屏切换快捷键
  18. mac下更新自带的PHP版本到5.6或7.0
  19. 用最速下降法求最优解
  20. 【2020】明哥版-JetBrains旗下常用开发工具教程目录更新中-建议收藏

热门文章

  1. Server 2008系统安装驱动提示“无法验驱动程序数字签名”怎么办?
  2. 中国重型包装行业竞争趋势与发展规模分析报告2022-2028年版
  3. 【月光博客】腾讯微信推出广告联盟
  4. 人大金仓(Kingbase)数据库迁移——使用大金仓数据库迁移工具进行迁移
  5. nacos 适配人大金仓数据
  6. 第三方Android应用商店也有安全问题
  7. LCD液晶显示屏颜色显示波长研究与总结?
  8. 为 Vue 项目添加 cnzz 统计
  9. 什么是云计算数据中心互连,云计算数据中心互连是如何运作的
  10. HTB_Secret