Based on the example here I have enabled spatialite in sqlite, the function enables that module. To do this you must link the sqlite3 library.
The modifications made are:
#include <sqlite3.h>
#include <QSqlDatabase>
#include <QSqlDriver>
#include <QSqlError>
int enable_spatialite(QSqlDatabase db){
QVariant v = db.driver()->handle();
if (v.isValid() && qstrcmp(v.typeName(), "sqlite3*")==0)
{
sqlite3_initialize();
sqlite3 *db_handle = *static_cast<sqlite3 **>(v.data());
if (db_handle != 0) {
sqlite3_enable_load_extension(db_handle, 1);
QSqlQuery query;
query.exec("SELECT load_extension('mod_spatialite')");
if (query.lastError() .isValid())
{
qDebug() << "Error: cannot load the Spatialite extension (" << query.lastError().text()<<")";
return 0;
}
qDebug()<<"**** SpatiaLite loaded as an extension ***";
query.exec("SELECT InitSpatialMetadata(1)");
if (query.lastError() .isValid())
{
qDebug() << "Error: cannot load the Spatialite extension (" << query.lastError().text()<<")";
return 0;
}
qDebug()<<"**** InitSpatialMetadata successful ***";
return 1;
}
}
return 0;
}
Example:
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName("memory.db");
if (!db.open()) {
qDebug()<<"not open";
}
qDebug()<<enable_spatialite(db);
QSqlQuery query;
qDebug()<<query.exec("CREATE TABLE test_geom (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, measured_value DOUBLE NOT NULL);");
qDebug()<<query.exec("SELECT AddGeometryColumn('test_geom', 'the_geom', 4326, 'POINT', 'XY');");
for(int i=0; i< 10; i++){
QString q = QString("INSERT INTO test_geom(id, name, measured_value, the_geom) VALUES (%1,'point %2', %3, GeomFromText('POINT(1.01 2.02)', 4326))")
.arg("NULL").arg(i).arg(i);
query.prepare(q);
qDebug()<< i<<query.exec();
}
qDebug()<<query.exec("SELECT id, name, measured_value, AsText(the_geom), ST_GeometryType(the_geom), ST_Srid(the_geom) FROM test_geom");
while (query.next()) {
QString str;
for(int i=0; i < query.record().count(); i++)
str += query.value(i).toString() + " ";
qDebug()<<str;
}
return a.exec();
}
Output:
**** SpatiaLite loaded as an extension ***
**** InitSpatialMetadata successful ***
1
true
true
0 true
1 true
2 true
3 true
4 true
5 true
6 true
7 true
8 true
9 true
true
"1 point 0 0 POINT(1.01 2.02) POINT 4326 "
"2 point 1 1 POINT(1.01 2.02) POINT 4326 "
"3 point 2 2 POINT(1.01 2.02) POINT 4326 "
"4 point 3 3 POINT(1.01 2.02) POINT 4326 "
"5 point 4 4 POINT(1.01 2.02) POINT 4326 "
"6 point 5 5 POINT(1.01 2.02) POINT 4326 "
"7 point 6 6 POINT(1.01 2.02) POINT 4326 "
"8 point 7 7 POINT(1.01 2.02) POINT 4326 "
"9 point 8 8 POINT(1.01 2.02) POINT 4326 "
"10 point 9 9 POINT(1.01 2.02) POINT 4326 "
The complete example can be found here.
This code has been tested on linux Arch Linux 4.11.3-1-ARCH, Qt 5.8
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…