MySQL---Database from getting started to Big God Series (ix)-read and write large text/binary data to the database in Java

Source: Internet
Author: User

Describes the text and graphics data type of MySQL: Text type:
Data type: Description------------------------------------------------------Char(size): holds a fixed-length string (which can contain letters, numbers, and special characters). Specifies the length of the string in parentheses. Most255a character. varchar (size): Holds variable-length strings (which can contain letters, numbers, and special characters). Specifies the maximum length of the string in parentheses. Most255a character. Note: If the value is longer than255, it is converted totextType. Tinytext: Maximum length of storage255Characters in a string.text: Maximum length of storage $,535Characters in a string. About $Kbblob: For BLOBs (BinaryLarge OBjects). Store up to $,535bytes of data. About $Kbmediumtext: Maximum length of storage -,777,215Characters in a string. -About -Mmediumblob: For BLOBs (BinaryLarge OBjects). Store up to -,777,215bytes of data. Longtext: Maximum length of storage4,294,967,295Characters in a string. About4Gblongblob: For BLOBs (BinaryLarge OBjects). Store up to4,294,967,295bytes of data.enum(x,y,z,etc.) Allows you to enter a list of possible values. (enumeration) can beenumThe list lists the largest65535A value. If the inserted value does not exist in the list, a null value is inserted. Note: These values are stored in the order that you entered them. You can enter possible values in this format:enum(' X ', ' Y ', ' Z ')SetAndenumSimilarSetcan contain up to -List items, butSetYou can store more than one value.
Read large text data to data written in Java: Prepare:
create table node( id int primary key, tx text );

Query table structure:

DESC table_name;

Configuration file in the previous blog note:
http://blog.csdn.net/qq_26525215/article/details/52153452

Util Tool Class Connection:
 PackageCn.hncu.util;ImportJava.io.IOException;ImportJava.sql.Connection;ImportJava.sql.DriverManager;ImportJava.sql.SQLException;ImportJava.util.Properties; Public  class connfactory {    Private StaticConnection con =NULL;//Static block    Static{Try{//Read configuration fileProperties p =NewProperties (); P.load (ConnFactory.class.getClassLoader (). getResourceAsStream ("Jdbc.properties")); String Drive = P.getproperty ("Driver"); String URL = p.getproperty ("url"); String user = P.getproperty ("username"); String Password = p.getproperty ("Password");            Class.forName (drive);        con = drivermanager.getconnection (url, user, password); }Catch(IOException e) {Throw NewRuntimeException ("configuration file Exception", e); }Catch(ClassNotFoundException e) {Throw NewRuntimeException ("Drive.class file Unexpected", e); }Catch(SQLException e) {Throw NewRuntimeException ("Database access exception occurred", e); }    } Public StaticConnectiongetconnection(){returnCon } Public Static void Main(string[] args)    {System.out.println (getconnection ()); }}
Write Text data:
Write large text data @Test public void WriteText () throws exception{Connection con = connfactory. getconnection();String sql =INSERT INTO node values (?,?);PreparedStatement PST = con. Preparestatement(SQL);Pst. Setint(1,1);This. GetClass(). getClassLoader(). GetResource(""). GetPath() got this project.. ClassThe absolute path of the root directory (bin/) InputStreaminch= This. GetClass(). getClassLoader(). getResourceAsStream("Cn/hncu/demo/jdbcdemo.java");System. out. println(This. GetClass(). getClassLoader(). GetResource(""). GetPath());A little bit of knowledge because we are getting the file under the bin directory, the SRC directory under the. JavaThe file will be compiled by MyEclipse. ClassThe file is placed in the corresponding bin directory. We created it directly under the src file.. JavaThe file cannot be copied to the Bin directory as myeclipse. If you need to read in. Javafile, you need to go directly to the. JavaThe file is placed in the corresponding bin directory. Pst. Setasciistream(2,inch);Pst. Executeupdate();Con. Close();}

Read Text data:
//Read large text data@Test Public void ReadText() throws Exception {Connection con = connfactory.getconnection (); String sql ="SELECT * from node where id=1";        PreparedStatement PST = con.preparecall (SQL); ResultSet rs = Pst.executequery ();//Because we only read one, there is no need to traverse it.         if(Rs.next ()) {//Read large text fieldInputStreaminch= Rs.getasciistream (2); BufferedReader br =NewBufferedReader (NewInputStreamReader (inch));//This is the knowledge of IoString line=""; while((Line=br.readline ())! =NULL) {System. out. println (line);//I'll output it directly, and you can output it to another file, which is essentially a flow. }        }    }

Write read binary (picture) data to data in Java:

Get ready:

create table img( id int primary key, img blob );

To write a picture:
Write picture @Test public void writeimg () throws sqlexception{Connection con = connfactory. getconnection();String sql ="INSERT into IMG values (?,?)";PreparedStatement PST = con. Preparestatement(SQL);Pst. Setint(1,1);InputStreaminch= Lobdemoimg. Class. getClassLoader(). getResourceAsStream("A.jpg");Pst. Setbinarystream(2,inch);Pst. Executeupdate();Con. Close();}

Read the picture and write to the file:
//Read pictures@Test Public void redaimg() throws SQLException, ioexception{Connection con = connfactory.getconnection (); String sql ="SELECT * from img where id=1";        PreparedStatement PST = con.preparestatement (SQL); ResultSet rs = Pst.executequery ();if(Rs.next ()) {InputStreaminch= Rs.getasciistream (2); FileOutputStream out=NewFileOutputStream (NewFile ("E:/a/a.jpg"));byte[] buf =New byte[1024x768];intlen=0; while((len=inch. Read (BUF))!=-1){ out. Write (BUF,0, Len); }inch. Close (); out. Close ();    } con.close (); }

Demo Result:

Although the big data can be stored, but generally do not store big data, because the efficiency is too low, unless the data is required to have a strong confidentiality, it will be stored like this!
The absolute path to storing that file is normal.

MySQL---Database from getting started to Big God Series (ix)-read and write large text/binary data to the database in Java

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.