Share on Google+Share on Google+

Java save file to database

In this section, you will learn how to insert file to database.

Java save file to database

In this section, you will learn how to insert file to database.

Description of code:

Firstly, we need to establish a connection between MySql database and java file with the help of various types of APIs, interfaces and methods. Then we have created an instance of File class and specify the file that is to be inserted.

Connection: This  interface specifies connection with specific databases like: MySQL, Ms-Access, Oracle etc and java files. The SQL statements are executed within the context of this interface.

Class.forName(String driver): It loads the driver.

DriverManager: This class controls a set of JDBC drivers. Each driver has to be register with this class.

getConnection(String url, String userName, String password): This method establishes a connection to specified database url. It is having three arguments:
        url: - Database url where stored or created your database
        username: - User name of MySQL
        password: -Password of MySQL 

PreparedStatement : This interface is slightly more powerful version of Statement which is used for executing the SQL statement.

Here is the code:

import java.sql.*;

public class FileToDatabase {
	public static void main(String[] args) throws Exception {
		String fileName = "C:/input.txt";
		File file = new File(fileName);
		FileInputStream fis = new FileInputStream(file);
		Connection conn = DriverManager.getConnection(
				"jdbc:mysql://localhost:3306/test", "root", "root");
		PreparedStatement pstmt = conn
				.prepareStatement("insert into file( file, file_data) values ( ?, ?)");
		pstmt.setString(1, file.getName());
		pstmt.setBinaryStream(2, fis, (int) file.length());

Through the above code, you can insert any file into the database.


Posted on: April 14, 2006 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.


Advertisement null