Java JDBC将一个文件夹的文件装载到PostgreSQL数据库BLOB列,并将BLOB列下载到另一个文件夹

DROP TABLE public.bindata;

CREATE TABLE public.bindata (
	id serial4 NOT NULL,
	"name" varchar NULL,
	"data" bytea NULL
);
package com.infotech.client;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import java.sql.DriverManager;

/**
 * @author KK JavaTutorials JDBC program to write or save binary data/BLOB data
 * in database
 */
public class SaveBinaryFilesInDBClientTest {

    public static void main(String[] args) throws SQLException, ClassNotFoundException {
        String DB_DRIVER_CLASS = "org.postgresql.Driver";
        String DB_USERNAME = "postgres";
        String DB_PASSWORD = "postgres";
        String DB_URL = "jdbc:postgresql://127.0.0.1:5432/testdb";

        Class.forName(DB_DRIVER_CLASS);

        String SQL = "INSERT INTO bindata (name,data)VALUES(?,?)";
        Path dir = Paths.get("InputFiles");
        try ( Stream<Path> list = Files.list(dir);  Connection connection = DriverManager.getConnection(DB_URL, DB_USERNAME, DB_PASSWORD);  PreparedStatement ps = connection.prepareStatement(SQL)) {
            /*
			 *Below line belongs to JDK 1.8 API so make sure you are running this code on JDK 1.8.
			 *And you IDE pointing to compiler version 1.8
             */
            List<Path> pathList = list.collect(Collectors.toList());
            System.out.println("Following files are saved in database..");
            for (Path path : pathList) {
                System.out.println(path.getFileName());
                File file = path.toFile();
                String fileName = file.getName();
                long fileLength = file.length();

                ps.setString(1, fileName);

                FileInputStream fis = new FileInputStream(file);
                ps.setBinaryStream(2, fis, fileLength);

                ps.addBatch();
            }
            System.out.println("----------------------------------------");
            int[] executeBatch = ps.executeBatch();
            for (int i : executeBatch) {
                System.out.println(i);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
package com.infotech.client;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import java.sql.DriverManager;

/**
 * @author KK JavaTutorials JDBC program to read binary data/BLOB data from
 * database and write into local disk.
 */
public class DownloadBinaryFilesFromDBClientTest {

    public static void main(String[] args) throws SQLException, ClassNotFoundException {
        String DB_DRIVER_CLASS = "org.postgresql.Driver";
        String DB_USERNAME = "postgres";
        String DB_PASSWORD = "postgres";
        String DB_URL = "jdbc:postgresql://127.0.0.1:5432/testdb";

        Class.forName(DB_DRIVER_CLASS);
        String SQL = "SELECT * FROM bindata";
        try ( Connection connection = DriverManager.getConnection(DB_URL, DB_USERNAME, DB_PASSWORD);  PreparedStatement ps = connection.prepareStatement(SQL);  ResultSet rs = ps.executeQuery()) {
            System.out.println("Following flies are downloaded from database..");
            while (rs.next()) {
                int fileId = rs.getInt("id");
                String fileName = rs.getString("name");
                System.out.println("File Id:" + fileId);
                System.out.println("File Name:" + fileName);

//                Blob blob = rs.getBlob("data");
//                InputStream inputStream = blob.getBinaryStream();
//
//                System.out.println("-----------------------------------");
//                Files.copy(inputStream, Paths.get("DownLoadFiles/" + fileName));
                File myFile = new File("DownLoadFiles/" + fileName);

                try ( FileOutputStream fos = new FileOutputStream(myFile)) {

                    byte[] buf = rs.getBytes("data");
                    int len = buf.length;
                    fos.write(buf, 0, len);
                }

            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

当然可以!以下是一个示例的Python脚本,用于将一个JSON文件导入到PostgreSQL数据库中: ```python import json import psycopg2 # 定义数据库连接参数 db_host = 'your_host' db_port = 'your_port' db_name = 'your_database_name' db_user = 'your_username' db_password = 'your_password' # 定义JSON文件路径 json_file_path = 'path_to_your_json_file.json' # 读取JSON文件 with open(json_file_path, 'r') as file: json_data = json.load(file) # 建立与PostgreSQL数据库的连接 conn = psycopg2.connect( host=db_host, port=db_port, dbname=db_name, user=db_user, password=db_password ) # 创建游标对象 cursor = conn.cursor() # 将JSON数据插入到数据库中 for data in json_data: # 根据JSON数据的结构和数据库表的结构进行相应的操作 # 这里假设JSON数据中的键名和数据库表的名一致 # 以下是一个示例,你需要根据实际情况进行修改 sql = "INSERT INTO your_table_name (column1, column2) VALUES (%s, %s)" values = (data['key1'], data['key2']) # 执行SQL语句 cursor.execute(sql, values) # 提交事务并关闭连接 conn.commit() cursor.close() conn.close() print("数据导入完成!") ``` 请替换代码中的以下部分来适应你的实际情况: - `your_host`:你的PostgreSQL数据库的主机地址 - `your_port`:你的PostgreSQL数据库的端口号 - `your_database_name`:你要连接的数据库名称 - `your_username`:你的数据库用户名 - `your_password`:你的数据库密码 - `path_to_your_json_file.json`:你的JSON文件路径 - `your_table_name`:你要插入数据的数据库表名 - `column1, column2`:你要插入数据的表的名 请注意,这只是一个示例,你需要根据你的实际情况进行适当的修改。同时,请确保你已经安装了`psycopg2`模块,可以通过以下命令进行安装: ``` pip install psycopg2 ``` 希望这可以帮助到你!如果还有其他问题,请随时询问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值