Java connects and stores images with Eclipse and MySQL databases--store pictures

Source: Internet
Author: User

import java.io.file;import java.io.fileinputstream;import java.io.inputstream;import  java.sql.connection;import java.sql.drivermanager;import java.sql.preparedstatement;public  Class insertimage { public static void main (String[]args)  throws  exception{   string user =  "root";//Database Password    string driver  =  "Com.mysql.jdbc.Driver";//Database driver       string password =   "040694zhang";//Database login password       String url =  "jdbc:mysql:// LOCALHOST:4017/IMAGE?CHARACTERENCODING=GBK ";//Database address, indicating the character set used       class.forname ( driver);//Load Driver       connection conn = drivermanager.getconnection (Url,user,password);//Get Connection object       preparedstatement ps ;// Declares a PreparedStatement object ps  &nBsp;   file file = new file ("pic/2.jpg");//Get the picture file to be stored        inputstream in = new fileinputstream (file);//Get files Input stream        byte[] b = new byte[in.available ()];//declares a binary array, length is the length of the file input stream        in.read (b);//The file is read into a binary array by the input stream       string sql  =  "Insert into photo (Name,photo)  values (' Z ',?)";       ps = conn.preparestatement (SQL);//Execute SQL statement        ps.setbytes (1, b);; /fill parameter       ps.executeupdate ();//update       in.close () ;//close file Input stream       ps.close ();//Turn off PS object        Conn.close ();//connection close  }}

Convert the picture file you want to store into a binary stream, and then enter it into the database. Where the database is called image, the table is photo, has two columns name, is a varchar (20) type, and the photo column is of type BLOB.

This article is from the "low-key Temperament" blog, please be sure to keep this source http://6641091.blog.51cto.com/6631091/1543304

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.