Sunday, 19 July 2015

SAVING IMAGES IN MYSQL UING JAVA/PYTHON

hi in this tutorial we are going to store how to store binary data in java and python .image and pdf are stored as binary format


using java

package mysql;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class BinaryPicture {
public static void main(String[] args) throws ClassNotFoundException, SQLException, FileNotFoundException {
Class.forName("com.mysql.jdbc.Driver");
Connection con= DriverManager.getConnection("jdbc:mysql://localhost:3306/binarymanipulation", "root", "solomon");
PreparedStatement pstmt = con.prepareStatement("insert into images values(?,?,?)");
File file = new File("/home/solomon/Downloads/javapic.jpeg");
System.out.println(file.exists());
FileInputStream is = new FileInputStream(file);
int length= (int)file.length();
System.out.println(length);
 pstmt.setString(1, "javacomplete edition");
 pstmt.setInt(2,length );
 pstmt.setBlob(3, is);
int i=  pstmt.executeUpdate();
System.out.println(i);
 pstmt.close();
 con.close();


}

}

using python

import mysql.connector
import base64

conn = mysql.connector.Connect(user="root",passwd="solomon",host="localhost",db="binarymanipulation",port="3306")

cursor =conn.cursor();
with open('/home/solomon/Downloads/javapic.jpeg', 'rb') as image:
        imageraw = image.read()
s=(imageraw,)
sql = "INSERT INTO images(id,size,image) VALUES('PYTHON',245, %s)"
cursor.execute(sql,s)
conn.commit();
conn.close();


No comments:

Post a Comment