Home Tutorial Java Core Files Java save file to database

 
 

Share on Google+Share on Google+
Java save file to database
Posted on: April 14, 2006 at 12:00 AM
Advertisement
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.io.*;
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);
		Class.forName("com.mysql.jdbc.Driver");
		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());
		pstmt.executeUpdate();
	}
}

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

Advertisement

Related Tags for Java save file to database:


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.

Posted on: April 14, 2006

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com