I found out on the internet how to store the file body (usually about image) in the database, but found that most of the practices are to store the corresponding file path, when you need this file, you can query it by path. In this case, the file is stored in the database in an abstract way, and the ontology is not stored, this may be due to efficiency and database size considerations (I do not know much about the database ). I tried it because I was interested in QT some time ago and found that I could use a third-party database.
(1) Create a database connection
Bool mydatabase: createconnection ()
{
DB = qsqldatabase: adddatabase ("qsqlite ");
DB. setdatabasename ("mydb. DB ");
If (! DB. open ()){
Qdebug () <"can't open database >>>>> mydb. DB ";
Exit (-1 );
}
Return true;
}
The third-party database SQLite is used. The database name is mydb. dB, and then the database is opened.
(2) create a table required for storage
Bool mydatabase: createtable ()
{
Qstringlist tablelist = dB. Tables ();
Qsqlquery query (db );
If (! Tablelist. Contains ("Files "))
{
Qstring createtable = "create table files (ID integer primary key ,"
"FILENAME varchar (128) Unique, filecontent BLOB )";
If (! Query.exe C (createtable ))
{
Qdebug () <query. lasterror ();
Exit (-1 );
}
}
Return true;
}
To check whether a related table exists and does not exist, use "create table files (ID integer primary key, filename varchar (128) Unique, filecontent BLOB)"; to create a file table.
(3) the storage file name is
Bool mydatabase: storefile (qstring filename)
{
Qsqlquery query (db );
Qfile file (filename );
If (file. Open (qiodevice: readonly )){
Qbytearray & tdata = file. readall ();
Qbytearray DATA = qcompress (tdata, 9 );
Query. Prepare ("insert into files (ID, filename, filecontent )"
"Values (null,: filename,: filecontent )");
Query. bindvalue (": FILENAME", filename );
Query. bindvalue (": filecontent", data );
If (! Query.exe C ())
{
Qdebug () <query. lasterror ();
Return false;
}
}
Else
{
Return false;
}
Return true;
}
The basic idea is to replace the file named filename with qbytearray, then use a third-party zlib for the highest level of compression, and then store
(4) from the database
Bool mydatabase: GetFile (qstring filename)
{
Qsqlquery query (db );
Query. Prepare ("select filecontent from files ");
Query.exe C ();
Query. Next ();
Qbytearray tdata = query. Value (0). tobytearray ();
Qbytearray DATA = quncompress (tdata );
Qfile file (filename );
If (file. Open (qiodevice: writeonly ))
{
File. Write (data );
File. Close ();
}
Else
{
Return false;
}
Return true;
}
Because it is just an attempt, you only need to read one and name it filename. The basic idea is to convert the content stored in the database into qbytearray, decompress it, and write it into the file.
This example is only an example, and I hope it will be helpful to you.