Upload java files to the database as blob

Source: Internet
Author: User

There is nothing. Take MYSQL as an example;

Create a table in the database,

Write a test class later

Test by myself is absolutely available

Import java. Io. bytearrayinputstream;
Import java. Io. file;
Import java. Io. fileinputstream;
Import java. SQL. connection;
Import java. SQL. drivermanager;
Import java. SQL. preparedstatement;

/**
* The test is successful in the MySQL database, and it is found that the Blob database of MySQL does not support image storage, only supports
* Local data storage of less than 65535 bytes. However, other large databases support image storage.
*/
Public class insertblob {

Public static void main (string [] ARGs ){

Try {
File F = new file ("C: \ bsmain_runtime.log ");

Long length = f. Length ();
Fileinputstream FCM = new fileinputstream ("C: \ bsmain_runtime.log ");

Byte [] imagebytes = new byte [(INT) length];

Int bytelength = FCM. Read (imagebytes, 0, (INT) length );

Bytearrayinputstream BAIS = new bytearrayinputstream (imagebytes );


Class. forname ("com. MySQL. JDBC. Driver ");
Connection con = drivermanager. getconnection ("JDBC: mysql: // localhost/test", "root", "Java ");

Preparedstatement pstmt = NULL;

/*
Create Table mypicture
(
Name varchar (20 ),
Image blob
);
*/


Pstmt = con. preparestatement ("insert into mypicture (name, image) values (?,?) ");

Pstmt. setstring (1, "001 ");

Pstmt. setbinarystream (2, BAIS, bytelength );
Pstmt.exe cuteupdate ();

System. Out. println ("file length:" + length );
System. Out. println ("Byte Length:" + bytelength );

System. Out. println ("inserted successfully .");
} Catch (exception e ){
E. printstacktrace ();

}

}

}

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.