java数据库编程——执行查询操作(一)

【0】README

1) 本文部分文字描述和source code 均转自 core java volume 2 , 旨在理解 java数据库编程——执行查询操作 的基础知识 ;
2) 本文和 java数据库编程——执行查询操作(二) 是姊妹篇, 共同组成了 java数据库编程——执行查询操作的全部内容, for java数据库编程——执行查询操作(二), please visit http://blog.csdn.net/PacosonSWJTU/article/details/50629580
3)for database connection config, please visit : https://github.com/pacosonTang/core-java-volume/blob/master/coreJavaAdvanced/chapter4/database.properties


【1】预备语句(prepared statement)

1) 预备语句(prepared statement): 它是 Statement 语句对象;
2)problem+solution:

  • 2.1)problem:我们没有必要在每次开始一个查询是都建立新的查询语句;

    select books.price, books.title
    from books, publishers
    where books.publisher_id = publishers.publisher_id
    and publishers.name = the name from the list box

  • 2.2)solution: 而是准备一个带有宿主变量的查询语句,每次查询时只需要为该变量填入不同的字符串就可以反复多次使用该语句;

    String publisherQuery =
    “select books.price, books.title ” +
    “from books, publishers ” +
    “where books. …. and publishers.name = ?” (干货——预备语句中的宿主变量?)

3)PreparedStatement set 方法: 在执行预备语句前, 必须使用 set 方法将变量 绑定到实际的值上;

stat.setString(1, publisher);
除非使用 set 或者 clearParameters 方法,否则所有宿主变量的绑定都不会改变;

4)价格更新操作可以有 update 语句实现:

  • 4.1)请注意: 我们调用的是 executeUpdate 方法, 而非executeQuery 方法, 因为 update 语句不返回结果集。 executeUpdate 的返回值为 被修改过的行数;(干货——executeUpdate 的返回值为 被修改过的行数)

    int r = stat.executeUpdate();

5)看个荔枝:(低效率的java 数据库查询代码)

select books.price, books.title from books, booksAuthors, authors, publishers where authors.author_id = booksAutors.author_id and booksAuthors.isbn=books.isbn and books.publisher_id=publisher.publisher_id and authors.name=? and publisher.name=?

对以上java数据库查询代码的分析(Analysis)

  • A1)在相关的 Connection对象关闭后, PreparedStatement 对象就变得无效了。 不过, 许多数据库通常都会自动缓存预备语句。如果相同的查询被预备了两次, 数据库通常会直接重用查询策略;
  • A2)许多coders 都不喜欢用 如此复杂的sql 语句,比较常见的方法是使用大量的 java 代码来迭代多个结果集, 但是这种方法是低效的; (干货——比较常见的方法是使用大量的 java 代码来迭代多个结果集, 但是这种方法是低效的)
  • A3)通常,使用数据库的查询代码要比使用 java 代码好得多——这是数据库的一个优点, 一般而言,可以使用 sql 语句解决的问题,就不要使用 java 程序; (干货——一般而言,可以使用 sql 语句解决的问题,就不要使用 java 程序)

6) 利用预备语句插入和查询的荔枝

  • 6.1)for full source code, please visit https://github.com/pacosonTang/core-java-volume/blob/master/coreJavaAdvanced/chapter4/execute_select/MyGetPrimaryKey.java
  • 6.2)key source code at a glance
public static Connection getConnection() throws IOException, SQLException{Properties prop = new Properties();try(InputStream in = Files.newInputStream(Paths.get(cur_dir + "database.properties"))){prop.load(in);}String drivers = prop.getProperty("jdbc.drivers");if(drivers != null){System.setProperty("jdbc.drivers", drivers); // register drivers for accessing database }String url = prop.getProperty("jdbc.url");String user = prop.getProperty("jdbc.username");String pass = prop.getProperty("jdbc.password");return DriverManager.getConnection(url, user, pass);}// PreparedStatement for query operationpublic static void main3(String[] args) throws SQLException, IOException{       try{try(Connection conn = getConnection()){// String sql = "insert employee(name, salary, address) values('zhangsan',1000,'beijing')";String sql = "select * from employee where id > ?";PreparedStatement stat = conn.prepareStatement(sql);stat.setInt(1, 12);ResultSet rs = stat.executeQuery();// attention for not writing stat.executeQuery(sql);while(rs.next()){System.out.println(rs.getInt(1) + ", " + rs.getString(2) + ", " + rs.getDouble(3) + ", " + rs.getString(4));}}}catch(Exception e){e.printStackTrace();}}   // PreparedStatement for insert operationpublic static void main2(String[] args) throws SQLException, IOException{       try{try(Connection conn = getConnection()){// String sql = "insert employee(name, salary, address) values('zhangsan',1000,'beijing')";String sql = "insert into employee(name,salary,address) values(?,?,?)";//Statement stat = conn.createStatement();PreparedStatement stat = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);String[] names = {"lisi", "wangwu", "zhaoliu"};double[] salary = {120, 110, 999};String[] address = {"chengdu", "shanghai", "shenzheng"};for (int i = 0; i < address.length; i++){// 除非使用 set 或者 clearParameters 方法,否则所有宿主变量(?)的绑定都不会改变;stat.setString(1, names[i]);stat.setDouble(2, salary[i]);stat.setString(3, address[i]);stat.executeUpdate();// attention for not writing stat.executeUpdate(sql);}               sql = "select * from employee";ResultSet rs = stat.executeQuery(sql);while(rs.next()){System.out.println(rs.getInt(1) + ", " + rs.getString(2) + ", " + rs.getDouble(3) + ", " + rs.getString(4));}}}catch(Exception e){e.printStackTrace();}}   
  • 其中, database.properties 文件内容如下(后面不在累述):

    jdbc.drivers=com.mysql.jdbc.Driver
    jdbc.url=jdbc:mysql://localhost:3306/testCoreJava
    jdbc.username=root
    jdbc.password=root

  • 6.3)relative printing results as follows
    这里写图片描述
    这里写图片描述


【2】读写 LOB(Large OBject)

1)大对象(LOB):许多数据库还存储大对象, 如图片和其它数据; (干货——LOB定义)

  • 1.1)BLOB+CLOB:二进制大对象称为BLOB, 字符型大对象被称为 CLOB;
  • 1.2)要读取 LOB: 需要执行 select 语句,然后在 ResultSet 上调用 getBlob 或getClob 方法, 这样就可以获得 Blog 或 Clob 类型的对象了;
  • 1.3)要从 Blob 中获取二进制数据:可以调用 getBytes 或 getInputStream ;
  • 1.4)获取Clob的字符数据:类似地, 如果获取了 Clob对象, 那么就可以调用getSubString 或 getCharacterStream方法来获取其中的字符数据;

2)看个荔枝: 如何将图片保存到数据库和如何从数据库获取图片并保存到本地 (干货荔枝——如何向数据库插入图片和从数据库中获取图片)
Attention)

  • A1)通过JDBC将图片插入到数据库和从数据库取出图片本保存到本地的idea, 参见 http://blog.csdn.net/pacosonswjtu/article/details/50628628
  • A2)荔枝中 关于存储图片到本地的代码转自 http://www.codejava.net/java-se/jdbc/read-file-data-from-database-using-jdbc

  • A3)for full source code, please visit : https://github.com/pacosonTang/core-java-volume/blob/master/coreJavaAdvanced/chapter4/execute_select/JDBCReadWriteImage.java

  • A4)key source code at a glance :
package com.corejava.chapter4;import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;public class JDBCReadWriteImage
{private static String cur_dir = System.getProperty("user.dir") + File.separator +  "com" + File.separator + "corejava" + File.separator +  "chapter4" + File.separator;// insert and select blob objpublic static void main(String[] args){try{try(Connection conn = getConnection()){// inserting starts.String sql = "insert into employee(name, headportrait) values(?,?)";PreparedStatement insertStat = conn.prepareStatement(sql);insertStat.setString(1, "imageAdmin");              insertStat.setBlob(2, new FileInputStream(new File(cur_dir+"jdbc.jpg")));if(insertStat.executeUpdate() != 0){System.out.println("successful inserting!");}else{System.out.println("failed inserting!");}// inserting ends.// query starts.sql = "select headportrait from employee where name = 'imageAdmin'";Statement stat = conn.createStatement();                                ResultSet rs = stat.executeQuery(sql);int i = 1;while(rs.next()){Blob blob = rs.getBlob(1);InputStream instream = blob.getBinaryStream();OutputStream outstream = new FileOutputStream(new File(cur_dir + "blog" + (i++) +".jpg"));byte[] buffer = new byte[1024];int readLength = -1;while((readLength = instream.read(buffer)) != -1){outstream.write(buffer, 0, readLength);}System.out.println("successful query and saving the file !");}// query ends.stat.close();conn.close();}}catch(Exception e){e.printStackTrace();}}public static Connection getConnection() throws IOException, SQLException{Properties prop = new Properties();try(InputStream in = Files.newInputStream(Paths.get(cur_dir + "database.properties"))){prop.load(in);}String drivers = prop.getProperty("jdbc.drivers");if(drivers != null){System.setProperty("jdbc.drivers", drivers); // register drivers for accessing database }String url = prop.getProperty("jdbc.url");String user = prop.getProperty("jdbc.username");String pass = prop.getProperty("jdbc.password");return DriverManager.getConnection(url, user, pass);}
}
  • A5) relative printing results as follows:
    这里写图片描述
    这里写图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/331445.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Shell入门(九)之字符串比较

一、字符串比较 字符串比较符&#xff1a;、!、-z、-n、str 实际上&#xff0c;shell不区分数值与字符串类型&#xff0c;数值也可以使用上面比较。 a"mk" b"maokun" 运算符说明举例检测两个字符串是否相等&#xff0c;相等返回 true。[ $a $b ] 返回…

java中将毫秒转换成时间_在Java中将时间单位转换为持续时间

java中将毫秒转换成时间java.util.concurrent.TimeUnit以给定的粒度单位表示Java中的持续时间&#xff0c;并提供跨单位转换的实用方法。 java.util.concurrent.TimeUnit最早是在Java早期&#xff08;1.5&#xff09;引入的&#xff0c;但自那时以来已经扩展了好几次。 在此博客…

java数据库编程——执行查询操作(二)

【0】README 1&#xff09; 本文部分文字描述和source code 均转自 core java volume 2 &#xff0c; 旨在理解 java数据库编程——执行查询操作&#xff08;二&#xff09; 的基础知识 &#xff1b; 2&#xff09; 本文和 java数据库编程——执行查询操作&#xff08;一&…

Shell入门(十)之echo

一、echo参数 echo [参数选项] 字符串 参数选项 -e 解析字符串中的转义字符&#xff0c;如\n -E 这是默认设置&#xff0c;不解析转义字符 -n 不输出换行&#xff0c;可以使用echo -e 字符串"\c" 代替 #!/bin/bash a"abc\n" echo $a echo -e…

vaadin_Vaadin提示:延迟加载和商品标识

vaadin延迟加载 在Vaadin中使用网格&#xff0c;树或任何其他多值组件时&#xff0c;您通常希望显示数据库表中的数据&#xff0c;并且通常数据库中有多行。 在这种情况下&#xff0c;加载数千甚至数百万条记录是没有意义的&#xff0c;这将是一个巨大的性能问题。 对于此用例&…

com.mysql.jdbc.NotUpdatable: Result Set not updatable (references no primary keys).(解决方法)

【1】异常详细信息 com.mysql.jdbc.NotUpdatable: Result Set not updatable (references no primary keys). This result set must come from a statement that was created with a result set type of ResultSet.CONCUR_UPDATABLE, the query must select only one table, …

jdk 取整数_JDK 15中的确切绝对整数

jdk 取整数JDK 15 Early Access Build b18向Math和StrictMath类引入了新方法&#xff0c;这些方法将在提供的值超出方法所支持的范围时抛出ArithmeticException &#xff0c;而不会溢出。 这些方法为Java中的“绝对值”概念带来了Math.addExact &#xff0c; Math.subtractExac…

java数据库编程——可滚动和可更新的结果集

【0】README 1&#xff09; 本文部分文字描述转自 core java volume 2 &#xff0c; 测试源代码均为原创&#xff0c; 旨在理解 java数据库编程——可滚动和可更新的结果集 的基础知识 &#xff1b; 2&#xff09;for database connection config, please visit &#xff1a;…

Spring入门(四)之BeanFactory

一、BeanFacotry访问一个Spring bean容器的根接口。这是一个Bean容器基本客户端视图&#xff1b;进一步的接口如ListableBeanFactory和configurablebeanfactory供特定用途。此接口由包含许多bean定义的对象来实现&#xff0c;每个对象都有唯一的字符串名称标识。根据bean定义&a…

apache derby_Apache Derby数据库JVM安全策略

apache derby抽象 我已经发布了许多有关Derby的博客&#xff1a; Derby数据库备份 同一主机上的多个Derby网络服务器 Apache Derby数据库用户和权限 与Maven和内存中Derby数据库的集成测试 这本不打算是一个系列。 但是多年来&#xff0c;我越来越多地使用Derby。 我开始将…

java数据库编程——事务

【0】README 1&#xff09; 本文部分文字描述转自 core java volume 2 &#xff0c; 测试源代码均为原创&#xff0c; 旨在理解 java数据库编程——事务 的基础知识 &#xff1b; 2&#xff09;for database connection config, please visit &#xff1a; https://github.co…

算法九之基数排序

一、基数排序 &#xff08;1&#xff09;基数排序的简介 基数排序不同于其他的排序算法&#xff0c;它不是基于比较的算法。基数排序是一种借助多关键字排序的思想对单逻辑关键字进行排序的方法。它是一种稳定的排序算法。  通常用于对数的排序选择的是最低位优先法&#xff…

在Spring中使用多个动态缓存

在第三篇有关Spring&#xff08;长时间&#xff09;的缓存管理器的文章中&#xff0c;我想通过展示如何配置多个动态创建缓存的缓存管理器来扩展前 两个 。 Spring具有CompositeCacheManager &#xff0c;从理论上讲&#xff0c;它应该允许使用多个缓存管理器。 它通过询问基础…

java数据库编程——元数据(metadata)+web 与企业应用中的连接管理

【0】README 1&#xff09; 本文部分文字描述转自 core java volume 2 &#xff0c; 测试源代码均为原创&#xff0c; 旨在理解 java数据库编程——元数据&#xff08;metadata&#xff09;web 与企业应用中的连接管理 的基础知识 &#xff1b; 2&#xff09;for database co…

托管 非托管_如何在托管的Kubernetes上备份Neo4J

托管 非托管在下面的视频中&#xff0c;我将解释如何对在托管Kubernetes环境中运行的Neo4J实例进行完整和增量备份。 我们将使用其他Pod进行远程备份&#xff0c;并将备份数据存储在托管环境提供的持久卷上。 如果您想知道如何将Neo4J部署到托管Kubernetes&#xff0c;请查看以…

java国际化——Locale+数字格式

【0】README 1&#xff09; 本文部分文字描述转自 core java volume 2 &#xff0c; 测试源代码均为原创&#xff0c; 旨在理解 java国际化——Locale数字格式 的基础知识 &#xff1b; 2&#xff09; java 编程语言是第一个设计成为全面支持国际化的语言。 2.1&#xff09;…

Linux指令类型(一)change指令

一、change指令 chattr chgrp chmod chown chfn chsh chroot 二、ch指令详细介绍 &#xff08;1&#xff09;chattr 全名&#xff1a;change attribute 作用&#xff1a;chattr命令用于改变文件属性 语法&#xff1a;chattr [-RV][-v<版本编号>]…

restful rest_HATEOAS的RESTful服务。 REST:刷新器

restful rest在这篇文章中&#xff0c;我们将介绍有关HATEOAS的RESTful服务的综合文章。 REST&#xff1a;刷新器。 1.简介 “不好了&#xff01; 请&#xff0c;不要再发表有关REST的文章&#xff01;” 你们中的许多人可能会尖叫&#xff0c;这是正确的。 已经出版了太多的…

Unicode® Character Name Index

【0】README 0.1&#xff09; there are unicodes for varients of alphabet a, for that of b, c, or d and so on, please visit http://unicode.org/charts/charindex.html [A] A WITH ACUTE, LATIN CAPITAL LETTER 00C1 A WITH ACUTE, LATIN SMALL LETTER 00E1 A WITH…