【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 語句實現:
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.java6.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); }String url = prop.getProperty(
"jdbc.url" );String user = prop.getProperty(
"jdbc.username" );String pass = prop.getProperty(
"jdbc.password" );
return DriverManager.getConnection(url, user, pass);}
public static void main3 (String[] args) throws SQLException, IOException{
try {
try (Connection conn = getConnection()){String sql =
"select * from employee where id > ?" ;PreparedStatement stat = conn.prepareStatement(sql);stat.setInt(
1 ,
12 );ResultSet rs = stat.executeQuery();
while (rs.next()){System.
out .println(rs.getInt(
1 ) +
", " + rs.getString(
2 ) +
", " + rs.getDouble(
3 ) +
", " + rs.getString(
4 ));}}}
catch (Exception e){e.printStackTrace();}}
public static void main2 (String[] args) throws SQLException, IOException{
try {
try (Connection conn = getConnection()){String sql =
"insert into employee(name,salary,address) values(?,?,?)" ;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++){stat.setString(
1 , names[i]);stat.setDouble(
2 , salary[i]);stat.setString(
3 , address[i]);stat.executeUpdate();} 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/50628628A2) 荔枝中 關于存儲圖片到本地的代碼轉自 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 .chapter 4import 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)}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:
總結
以上是生活随笔 為你收集整理的java数据库编程——执行查询操作(一) 的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔 網站內容還不錯,歡迎將生活随笔 推薦給好友。