1. 程式人生 > >javaweb學習總結—使用JDBC處理MySQL大資料

javaweb學習總結—使用JDBC處理MySQL大資料

只為成功找方法,不為失敗找藉口!

一、基本概念

  大資料也稱之為LOB(Large Objects),LOB又分為:clob和blob,clob用於儲存大文字,blob用於儲存二進位制資料,例如影象、聲音、二進位制文等。

  在實際開發中,有時是需要用程式把大文字或二進位制資料直接儲存到資料庫中進行儲存的。

  對MySQL而言只有blob,而沒有clob,mysql儲存大文字採用的是Text,Text和blob分別又分為:   TINYTEXT、TEXT、MEDIUMTEXT和LONGTEXT   TINYBLOB、BLOB、MEDIUMBLOB和LONGBLOB

二、搭建測試環境

大資料學習加群:868847735

2.1、搭建的測試專案架構

  如下:

  

2.2、編寫db.properties配置檔案

1 driver=com.mysql.jdbc.Driver
2 url=jdbc:mysql://localhost:3306/jdbcStudy
3 username=root
4 password=XDP

2.3、編寫JdbcUtils工具類

複製程式碼

 1 package me.gacl.utils;
 2 
 3 import java.io.InputStream;
 4 import java.sql.Connection;
 5 import java.sql.DriverManager;
 6 import java.sql.ResultSet;
 7 import java.sql.SQLException;
 8 import java.sql.Statement;
 9 import java.util.Properties;
10 
11 public class JdbcUtils {
12 
13     private static String driver = null;
14     private static String url = null;
15     private static String username = null;
16     private static String password = null;
17     
18     static{
19         try{
20             //讀取db.properties檔案中的資料庫連線資訊
21             InputStream in = JdbcUtils.class.getClassLoader().getResourceAsStream("db.properties");
22             Properties prop = new Properties();
23             prop.load(in);
24             
25             //獲取資料庫連線驅動
26             driver = prop.getProperty("driver");
27             //獲取資料庫連線URL地址
28             url = prop.getProperty("url");
29             //獲取資料庫連線使用者名稱
30             username = prop.getProperty("username");
31             //獲取資料庫連線密碼
32             password = prop.getProperty("password");
33             
34             //載入資料庫驅動
35             Class.forName(driver);
36             
37         }catch (Exception e) {
38             throw new ExceptionInInitializerError(e);
39         }
40     }
41     
42     /**
43     * @Method: getConnection
44     * @Description: 獲取資料庫連線物件
45     * @Anthor:孤傲蒼狼
46     *
47     * @return Connection資料庫連線物件
48     * @throws SQLException
49     */ 
50     public static Connection getConnection() throws SQLException{
51         return DriverManager.getConnection(url, username,password);
52     }
53     
54     /**
55     * @Method: release
56     * @Description: 釋放資源,
57     *     要釋放的資源包括Connection資料庫連線物件,負責執行SQL命令的Statement物件,儲存查詢結果的ResultSet物件
58     * @Anthor:孤傲蒼狼
59     *
60     * @param conn
61     * @param st
62     * @param rs
63     */ 
64     public static void release(Connection conn,Statement st,ResultSet rs){
65         if(rs!=null){
66             try{
67                 //關閉儲存查詢結果的ResultSet物件
68                 rs.close();
69             }catch (Exception e) {
70                 e.printStackTrace();
71             }
72             rs = null;
73         }
74         if(st!=null){
75             try{
76                 //關閉負責執行SQL命令的Statement物件
77                 st.close();
78             }catch (Exception e) {
79                 e.printStackTrace();
80             }
81         }
82         
83         if(conn!=null){
84             try{
85                 //關閉Connection資料庫連線物件
86                 conn.close();
87             }catch (Exception e) {
88                 e.printStackTrace();
89             }
90         }
91     }
92 }

複製程式碼

三、使用JDBC處理MySQL的大文字

  對於MySQL中的Text型別,可呼叫如下方法設定

1 PreparedStatement.setCharacterStream(index, reader, length);//注意length長度須設定,並且設定為int型

  對MySQL中的Text型別,可呼叫如下方法獲取

1 reader = resultSet. getCharacterStream(String columnLabel);2 string s = resultSet.getString(String columnLabel);

3.1、 測試範例

  1、編寫SQL測試指令碼

複製程式碼

1 create database jdbcstudy;
2 use jdbcstudy;
3 create table testclob
4 (
5          id int primary key auto_increment,
6          resume text
7 );

複製程式碼

  2、編寫測試程式碼如下:

複製程式碼

  1 package me.gacl.demo;
  2 
  3 import java.io.File;
  4 import java.io.FileReader;
  5 import java.io.FileWriter;
  6 import java.io.Reader;
  7 import java.sql.Connection;
  8 import java.sql.PreparedStatement;
  9 import java.sql.ResultSet;
 10 import me.gacl.utils.JdbcUtils;
 11 import org.junit.Test;
 12 
 13 /**
 14 * @ClassName: JdbcOperaClob
 15 * @Description: 使用JDBC操作MySQL的大文字
 16 * @author: 孤傲蒼狼
 17 * @date: 2014-9-19 下午10:10:04
 18 *
 19 */ 
 20 public class JdbcOperaClob {
 21 
 22     /**
 23     * @Method: add
 24     * @Description:向資料庫中插入大文字資料
 25     * @Anthor:孤傲蒼狼
 26     *
 27     */ 
 28     @Test
 29     public void add(){
 30         Connection conn = null;
 31         PreparedStatement st = null;
 32         ResultSet rs = null;
 33         Reader reader = null;
 34         try{
 35             conn = JdbcUtils.getConnection();
 36             String sql = "insert into testclob(resume) values(?)";
 37             st = conn.prepareStatement(sql);
 38             //這種方式獲取的路徑,其中的空格會被使用“%20”代替
 39             String path = JdbcOperaClob.class.getClassLoader().getResource("data.txt").getPath();
 40             //將“%20”替換回空格
 41             path = path.replaceAll("%20", " ");
 42             File file = new File(path);
 43             reader = new FileReader(file);
 44             st.setCharacterStream(1, reader,(int) file.length());
 45             int num = st.executeUpdate();
 46             if(num>0){
 47                 System.out.println("插入成功!!");
 48             }
 49             //關閉流
 50             reader.close();
 51         }catch (Exception e) {
 52             e.printStackTrace();
 53         }finally{
 54             JdbcUtils.release(conn, st, rs);
 55         }
 56     }
 57     
 58     /**
 59     * @Method: read
 60     * @Description: 讀取資料庫中的大文字資料
 61     * @Anthor:孤傲蒼狼
 62     *
 63     */ 
 64     @Test
 65     public void read(){
 66         Connection conn = null;
 67         PreparedStatement st = null;
 68         ResultSet rs = null;
 69         try{
 70             conn = JdbcUtils.getConnection();
 71             String sql = "select resume from testclob where id=2";
 72             st = conn.prepareStatement(sql);
 73             rs = st.executeQuery();
 74             
 75             String contentStr ="";
 76             String content = "";
 77             if(rs.next()){
 78                 //使用resultSet.getString("欄位名")獲取大文字資料的內容
 79                 content = rs.getString("resume");
 80                 //使用resultSet.getCharacterStream("欄位名")獲取大文字資料的內容
 81                 Reader reader = rs.getCharacterStream("resume");
 82                 char buffer[] = new char[1024];
 83                 int len = 0;
 84                 FileWriter out = new FileWriter("D:\\1.txt");
 85                 while((len=reader.read(buffer))>0){
 86                     contentStr += new String(buffer);
 87                     out.write(buffer, 0, len);
 88                 }
 89                 out.close();
 90                 reader.close();
 91             }
 92             System.out.println(content);
 93             System.out.println("-----------------------------------------------");
 94             System.out.println(contentStr);
 95         }catch (Exception e) {
 96             e.printStackTrace();
 97         }finally{
 98             JdbcUtils.release(conn, st, rs);
 99         }
100     }
101 }

複製程式碼

四、使用JDBC處理MySQL的二進位制資料

  對於MySQL中的BLOB型別,可呼叫如下方法設定:

1 PreparedStatement. setBinaryStream(i, inputStream, length);

  對MySQL中的BLOB型別,可呼叫如下方法獲取:

1 InputStream in  = resultSet.getBinaryStream(String columnLabel);
2 InputStream in  = resultSet.getBlob(String columnLabel).getBinaryStream(); 

 4.1、 測試範例

  1、編寫SQL測試指令碼

1 create table testblob
2 (
3      id int primary key auto_increment,
4      image longblob
5 );

  2、編寫測試程式碼如下:

複製程式碼

 1 package me.gacl.demo;
 2 
 3 import java.io.File;
 4 import java.io.FileInputStream;
 5 import java.io.FileOutputStream;
 6 import java.io.InputStream;
 7 import java.sql.Connection;
 8 import java.sql.PreparedStatement;
 9 import java.sql.ResultSet;
10 import me.gacl.utils.JdbcUtils;
11 import org.junit.Test;
12 
13 /**
14 * @ClassName: JdbcOperaClob
15 * @Description: 使用JDBC操作MySQL的二進位制資料(例如影象、聲音、二進位制文)
16 * @author: 孤傲蒼狼
17 * @date: 2014-9-19 下午10:10:04
18 *
19 */ 
20 public class JdbcOperaBlob {
21 
22     /**
23     * @Method: add
24     * @Description:向資料庫中插入二進位制資料
25     * @Anthor:孤傲蒼狼
26     *
27     */ 
28     @Test
29     public void add(){
30         Connection conn = null;
31         PreparedStatement st = null;
32         ResultSet rs = null;
33         try{
34             conn = JdbcUtils.getConnection();
35             String sql = "insert into testblob(image) values(?)";
36             st = conn.prepareStatement(sql);
37             //這種方式獲取的路徑,其中的空格會被使用“%20”代替
38             String path = JdbcOperaBlob.class.getClassLoader().getResource("01.jpg").getPath();
39             //將“%20”替換會空格
40             path = path.replaceAll("%20", " ");
41             File file = new File(path);
42             FileInputStream fis = new FileInputStream(file);//生成的流
43             st.setBinaryStream(1, fis,(int) file.length());
44             int num = st.executeUpdate();
45             if(num>0){
46                 System.out.println("插入成功!!");
47             }
48             fis.close();
49         }catch (Exception e) {
50             e.printStackTrace();
51         }finally{
52             JdbcUtils.release(conn, st, rs);
53         }
54     }
55     
56     /**
57     * @Method: read
58     * @Description: 讀取資料庫中的二進位制資料
59     * @Anthor:孤傲蒼狼
60     *
61     */ 
62     @Test
63     public void read() {
64         Connection conn = null;
65         PreparedStatement st = null;
66         ResultSet rs = null;
67         try {
68             conn = JdbcUtils.getConnection();
69             String sql = "select image from testblob where id=?";
70             st = conn.prepareStatement(sql);
71             st.setInt(1, 1);
72             rs = st.executeQuery();
73             if (rs.next()) {
74                 //InputStream in = rs.getBlob("image").getBinaryStream();//這種方法也可以
75                 InputStream in = rs.getBinaryStream("image");
76                 int len = 0;
77                 byte buffer[] = new byte[1024];
78                 
79                 FileOutputStream out = new FileOutputStream("D:\\1.jpg");
80                 while ((len = in.read(buffer)) > 0) {
81                     out.write(buffer, 0, len);
82                 }
83                 in.close();
84                 out.close();
85             }
86         } catch (Exception e) {
87             e.printStackTrace();
88         } finally {
89             JdbcUtils.release(conn, st, rs);
90         }
91     }
92 }

複製程式碼

  關於使用JDBC處理MySQL大資料的內容就總結這麼多!

大資料學習群: