· 9 years ago · Nov 08, 2016, 02:30 PM
1int main(int argc, char *argv[])
2{
3 QApplication a(argc, argv);
4
5 conect_to_log_db("./log.db");
6
7 unsigned char binary_data[1024];
8
9 for(unsigned int i = 0, value = 1; i < 1024; i++, value++)
10 {
11 binary_data[i] = value;
12 }
13 store_to_log_db("01/02/2012,13:03:58", binary_data, 1024);
14 ......
15}
16
17
18bool store_to_log_db(QString dateTime, unsigned char *data, unsigned int dataLength)
19{
20 QSqlQuery objQuery(objLogsDB);
21
22 QString query = "CREATE TABLE IF NOT EXISTS logTable(logDateTime VARCHAR(19), packet BLOB, direction INTEGER)";
23 objQuery.exec(query);
24
25 QByteArray dataArr;
26 dataArr.resize(dataLength);
27 for(unsigned int i = 0; i < dataLength; i++)
28 {
29 dataArr[i] = data[i];
30 }
31
32 QVariant blobData = dataArr.data();
33
34 objQuery.prepare("INSERT INTO logTable VALUES(:logDateTime,:packet,:direction)");
35 objQuery.bindValue(":logDateTime",dateTime);
36 objQuery.bindValue(":packet",blobData,QSql::In | QSql::Binary);
37 objQuery.bindValue(":direction",1);
38
39 qDebug() << objQuery.exec();
40
41 return true;
42}
43
44$sqlite3 log.db
45sqlite> .output try.txt
46sqlite> .dump
47sqlite> .quit
48
49// https://github.com/KubaO/stackoverflown/tree/master/questions/sqlite-blob-11062145
50#include <QtSql>
51
52int main()
53{
54 QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
55 db.setDatabaseName("./log.db");
56
57 if (!db.open()) { qDebug() << "can't open the database"; return 1; }
58
59 QSqlQuery query{db};
60
61 query.exec("DROP TABLE log");
62
63 if (!query.exec("CREATE TABLE log(packet BLOB)"))
64 qDebug() << "create table failed";
65
66 QVariant data[2] = {QByteArray{1024, 1}, QByteArray{2048, 2}};
67
68 query.prepare("INSERT INTO log VALUES(:packet)");
69
70 query.bindValue(":packet", data[0], QSql::In | QSql::Binary);
71 if (!query.exec()) qDebug() << "insert failed";
72
73 query.bindValue(":packet", data[1], QSql::In | QSql::Binary);
74 if (!query.exec()) qDebug() << "insert failed";
75
76 db.close();
77
78 if (!db.open()) { qDebug() << "can't reopen the database"; return 2; }
79
80 query.prepare("SELECT (packet) FROM log");
81 if (!query.exec()) qDebug() << "select failed";
82
83 for (auto const & d : data) if (query.next()) {
84 qDebug() << query.value(0).toByteArray().size() << d.toByteArray().size();
85 if (d != query.value(0)) qDebug() << "mismatched readback value";
86 }
87
88 db.close();
89}