SQL Server Insert varbinary using nanodbc library

qojgxg4l  于 2023-06-21  发布在  其他
关注(0)|答案(1)|浏览(115)

I want to read a JPG file in C++ and insert to a MicroSoft SQL Server 2014 (or 2019) database as varbinary(max) type via nanodbc ( doc is here and github is here ). There are several examples in the doc site. However, I find nothing about inserting varbinary . How can I do it? Any example or alternative library will be appreciated

bvn4nwqk

bvn4nwqk1#

std::vector<std::uint8_t>
utl::file2vec(
    const std::filesystem::path& file_path)
{
    std::ifstream instream(
        file_path, std::ios::in | 
        std::ios::binary);
    std::vector<uint8_t> data(
        (std::istreambuf_iterator<char>(instream)), 
        std::istreambuf_iterator<char>());
    return data;
}

int main()
{
    // Establishing connections
    nanodbc::connection connection("DRIVER={SQL Server};SERVER=...;DATABASE=test_1;;Trusted=true;");
    // or connection(connection_string, timeout_seconds);
    // or connection("data source name", "username", "password");
    // or connection("data source name", "username", "password", timeout_seconds);
    cout << "Connected with driver " << connection.driver_name() << endl;

    // Setup
    nanodbc::statement statement(connection);

    // Inserting values
    prepare(statement, NANODBC_TEXT("insert tb_2 values (?);"));
    vector<vector<uint8_t>> data;
    data.push_back(file2vec(R"(...\my_file.jpg)"));
    statement.bind(0, data);
    execute(statement);

    return 0;
}

相关问题