I have a database in Qt.
it has four tables: maingroup, subgroup, parts, and position.this is my database:
CREATE TABLE `maingroup` (
`groupName`TEXT NOT NULL UNIQUE,
PRIMARY KEY(`groupName`)
);
CREATE TABLE `subgroup` (
`sub` TEXT NOT NULL UNIQUE,
`main` TEXT NOT NULL,
PRIMARY KEY(`sub`),
FOREIGN KEY(`main`) REFERENCES `maingroup`(`groupName`) ON DELETE CASCADE
);
CREATE TABLE `parts` (
`ID` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
`Part_Number` TEXT,
`Type` TEXT NOT NULL,
`Value` TEXT,
`Voltage` TEXT,
`Quantity` TEXT,
`Position` TEXT,
`Picture` TEXT,
FOREIGN KEY(`Position`) REFERENCES `Position`(`Poistion`) ON DELETE CASCADE,
FOREIGN KEY(`Type`) REFERENCES `subgroup`(`sub`) ON DELETE CASCADE
);
Type in table parts is foreign key refers to column sub from table subgroup.
main in table subgroup is foreign key refers to column groupname in table maingroup.
my problem is when I try (delete from maingroup WHERE groupName= 'dd';) in DB Browser it deletes both parent and children.
But in QT this command(myQuery.exec("delete from maingroup WHERE groupName= 'dd'");) just deletes the parent field in maingroup table and not the child in subgroup and part table and the main column in subgroup table refers to a field in maingroup table that does not exist.
what is wrong here?what should i do?
You need to turn on the foreign-key pragma by executing another statement before your DELETE statement.
QSqlQuery q;
q.exec("PRAGMA foreign_keys = ON");
q.exec("DELETE FROM ...");
This was able to cascade deletes, and should also be sufficient to solve other foreign-key related issues.
Credits to this forum.qt.io post.
In addition to #TrebledJ correct and very helpful answer it's worth to mention two additional characteristics about the foreign-key pragma (in connection with Qt):
1. The pragma can set via QSqlDatabase, too.
So the following code has the same effect as #TrebledJ's example:
auto database = QSqlDatabase::database();
database.exec("PRAGMA foreign_keys = ON");
QSqlQuery query(database); // query "inherits" the pragma from database
query.exec("DELETE FROM ...");
2. This behavior even applies if opening and using the database happens at different places in the program.
Still the same effect:
Somewhere in initialization code:
// this calls database.open() implicit because database was not open before.
auto database = QSqlDatabase::database();
QSqlDatabase::database();
database.exec("PRAGMA foreign_keys = ON");
// make sure database.close() is NOT called!
Somewhere else in code
// you'll get the instance of your initialization code because database is already open (so QSqlDatabase::database() implements a singleton pattern).
// so pragma foreign_keys is still set to "ON"
auto database = QSqlDatabase::database();
QSqlQuery query(database);
query.exec("DELETE FROM ...");
This might be important to know if you want to understand why the foreign_keys pragma seems to only sometimes apply in your project (and sometimes not).
What I did
So I came to the conclusion to make sure to have ONE distinct place in my code where to explicit open the database (and configure the connection):
QString dbConnectionName = "My project database";
auto database = QSqlDatabase::database(dbConnectionName, true);
// configure the pragmas here
At all other places I avoid to (accidentally) open the database:
auto database = QSqlDatabase::database(dbConnectionName, false);
// e.g. use the database via queries ...
Related
Using Qt, I have to connect to a database and list column's types and names from a table. I have two constraints:
1 The database type must not be a problem (This has to work on PostgreSQL, SQL Server, MySQL, ...)
2 When I looked on the internet, I found solutions that work but only if there are one or more reocrd into the table. And I have to get column's type and name with or without record into this database.
I searched a lot on the internet but I didn't find any solutions.
I am looking for an answer in Qt/C++ or using a query that can do that.
Thanks for help !
QSqlDriver::record() takes a table name and returns a QSqlRecord, from which you can fetch the fields using QSqlRecord::field().
So, given a QSqlDatabase db,
fetch the driver with db.driver(),
fetch the list of tables with db.tables(),
fetch the a QSqlRecord for each table from driver->record(tableName), and
fetch the number of fields with record.count() and the name and type with record.field(x)
According to the previous answers, I make the implementation as below.It can work well, hope it can help you.
{
QSqlDatabase db = QSqlDatabase::addDatabase("QSLITE", "demo_conn"); //create a db connection
QString strDBPath = "db_path";
db.setDatabaseName(strDBPath); //set the db file
QSqlRecord record = db.record("table_name"); //get the record of the certain table
int n = record.count();
for(int i = 0; i < n; i++)
{
QString strField = record.fieldName(i);
}
}
QSqlDatabase::removeDatabase("demo_conn"); //remove the db connection
Getting column names and types is a database-specific operation. But you can have a single C++ function that will use the correct sql query according to the QSqlDriver you currently use:
QStringlist getColumnNames()
{
QString sql;
if (db.driverName.contains("QOCI", Qt::CaseInsensitive))
{
sql = ...
}
else if (db.driverName.contains("QPSQL", Qt::CaseInsensitive))
{
sql = ...
}
else
{
qCritical() << "unsupported db";
return QStringlist();
}
QSqlQuery res = db.exec(sql);
...
// getting names from db-specific sql query results
}
I don't know of any existing mechanism in Qt which allows that (though it might exist - maybe by using QSqlTableModel). If noone else knows of such a thing, I would just do the following:
Create data classes to store the information you require, e.g. a class TableInfo which stores a list of ColumnInfo objects which have a name and a type.
Create an interface e.g. ITableInfoReader which has a pure virtual TableInfo* retrieveTableInfo( const QString& tableName ) method.
Create one subclass of ITableInfoReader for every database you want to support. This allows doing queries which are only supported on one or a subset of all databases.
Create a TableInfoReaderFactory class which allows creation of the appropriate ITableInfoReader subclass dependent on the used database
This allows you to have your main code independent from the database, by using only the ITableInfoReader interface.
Example:
Input:
database: The QSqlDatabase which is used for executing queries
tableName: The name of the table to retrieve information about
ITableInfoReader* tableInfoReader =
_tableInfoReaderFactory.createTableReader( database );
QList< ColumnInfo* > columnInfos = tableInfoReader->retrieveTableInfo( tableName );
foreach( ColumnInfo* columnInfo, columnInfos )
{
qDebug() << columnInfo.name() << columnInfo.type();
}
I found the solution. You just have to call the record function from QSqlDatabase. You have an empty record but you can still read column types and names.
I've been trying to add a foreign key to my table using heidisql and I keep getting the error 1452.
After reading around I made sure all my tables were running on InnoDB as well as checking that they had the same datatype and the only way I can add my key is if I drop all my data which I don't intend to do since I have spent quite a few hours on this.
here is my table create code:
CREATE TABLE `data` (
`ID` INT(10) NOT NULL AUTO_INCREMENT,
#bunch of random other columns stripped out
`Ability_1` SMALLINT(5) UNSIGNED NOT NULL DEFAULT '0',
#more stripped tables
`Extra_Info` SET('1','2','3','Final','Legendary') NOT NULL DEFAULT '1' COLLATE 'utf8_unicode_ci',
PRIMARY KEY (`ID`),
UNIQUE INDEX `ID` (`ID`)
)
COLLATE='utf8_unicode_ci'
ENGINE=InnoDB
AUTO_INCREMENT=650;
here is table 2
CREATE TABLE `ability` (
`ability_ID` SMALLINT(5) UNSIGNED NOT NULL AUTO_INCREMENT,
#stripped columns
`Name_English` VARCHAR(12) NOT NULL COLLATE 'utf8_unicode_ci',
PRIMARY KEY (`ability_ID`),
UNIQUE INDEX `ability_ID` (`ability_ID`)
)
COLLATE='utf8_unicode_ci'
ENGINE=InnoDB
AUTO_INCREMENT=165;
Finally here is the create code along with the error.
ALTER TABLE `data`
ADD CONSTRAINT `Ability_1` FOREIGN KEY (`Ability_1`) REFERENCES `ability` (`ability_ID`) ON UPDATE CASCADE ON DELETE CASCADE;
/* SQL Error (1452): Cannot add or update a child row: a foreign key constraint fails (`check`.`#sql-ec0_2`, CONSTRAINT `Ability_1` FOREIGN KEY (`Ability_1`) REFERENCES `ability` (`ability_ID`) ON DELETE CASCADE ON UPDATE CASCADE) */
If there is anything else I can provide please let me know this is really bothering me. I'm also using 5.5.27 - MySQL Community Server (GPL) that came with xampp installer.
If you are using HeidiSQL it is pretty easy.
Just see the image, click on the +Add to add foreign keys.
I prefer GUI way of creating tables and its attribute because it saves time and reduces errors.
I found it. Sorry everyone. The problem was that I had 0 as a default value for my fields while my original table had no value for 0.
Here is how you can do it ;
Create your Primary keys. For me this was straight forward so I won't post how to do that here
To create your FOREIGN KEYS you need to change the table / engine type for each table from MyIASM to InnoDb. To do this Select the table on the right hand side then select the OPTIONS tab on the right hand side and change the engine from MyIASM to InnoDb for every table.
I have an h2 database with two tables with foreign keys like
CREATE TABLE master (masterId INT PRIMARY KEY, slaveId INT);
CREATE TABLE slave (slaveId INT PRIMARY KEY, something INT,
CONSTRAINT fk FOREIGN KEY (slaveId) REFERENCES master(slaveId));
and need something like
DELETE master, slave FROM master m JOIN slave s ON m.slaveId = s.slaveId
WHERE something = 43;
i.e., delete from both tables (which AFAIK works in MySql). Because of the FOREIGN KEY I can't delete from the master first. When I start by deleting from the slave, I lose the information which rows to delete from the master. Using ON DELETE CASCADE would help, but I don't want it happen automatically every time. Should I allow it temporarily? Should I use a temporary table or what is the best solution?
Nobody answers, but it's actually trivial:
SET REFERENTIAL_INTEGRITY FALSE;
BEGIN TRANSACTION;
DELETE FROM master WHERE slaveId IN (SELECT slaveId FROM slave WHERE something = 43);
DELETE FROM slave WHERE something = 43;
COMMIT;
SET REFERENTIAL_INTEGRITY TRUE;
I have problems with a specific query when using the sqlite3_step function:
SELECT DISTINCT interfaces_int_id,device_dev_id FROM devInterface
INNER JOIN interfaces ON devInterface.interfaces_int_id=interfaces.intf_id
INNER JOIN nlink ON nlink.interfaces_intf_id=interfaces.intf_id
INNER JOIN neighbor ON neighbor.neighbor_id=nlink.neighbor_neighbor_id
I only posted the parts of the query which are relevant.
For querying the database, I use this code.
When debugging it, it hangs at
while(true)
{
---> result = sqlite3_step(statement);
if(result == SQLITE_ROW)
{
std::vector<std::string> values;
...
}
...
}
Depending on the database size, it sometimes takes minutes to get a result. But when using the Firefox plugin "SQLite Manager", it takes only 1-2 seconds.
In cases where the query takes several minutes, the "neighbor" and "nlink" tables have more than 150k entries.
For buliding the database, I used the Forward engineer feature of the MySQL Workbench tool, and modified the syntax to work for sqlite3:
CREATE TABLE IF NOT EXISTS device(dev_id INTEGER PRIMARY KEY AUTOINCREMENT, type INT, hwtype INT, dataSource INT, hostname TEXT, sw_version TEXT, stpBridgeID TEXT, stpProtocol TEXT);
CREATE TABLE IF NOT EXISTS interfaces(intf_id INTEGER PRIMARY KEY AUTOINCREMENT, intfName TEXT, intfType TEXT, phl INT, macAddress TEXT, ipAddress TEXT, subnetMask TEXT, duplex TEXT, speed TEXT, status TEXT, description TEXT, l2l3 TEXT, errLvl INT, loadLvl INT, channel_intf_id INT, vpc_id INT, CONSTRAINT fk_interfaces_interfaces1 FOREIGN KEY (channel_intf_id) REFERENCES interfaces (intf_id) ON DELETE CASCADE ON UPDATE CASCADE);
CREATE TABLE IF NOT EXISTS devInterface (interfaces_int_id INT, device_dev_id INT, cdp_cdp_id INT, PRIMARY KEY (interfaces_int_id, device_dev_id, cdp_cdp_id), CONSTRAINT fk_dev_interface_interfaces1 FOREIGN KEY (interfaces_int_id) REFERENCES interfaces (intf_id) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT fk_dev_interface_device1 FOREIGN KEY (device_dev_id) REFERENCES device (dev_id) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT fk_devInterface_cdp1 FOREIGN KEY (cdp_cdp_id) REFERENCES cdp (cdp_id) ON DELETE CASCADE ON UPDATE CASCADE);
CREATE TABLE IF NOT EXISTS neighbor (neighbor_id INTEGER PRIMARY KEY AUTOINCREMENT, l2_addr TEXT NULL , l3_addr TEXT NULL);
CREATE TABLE IF NOT EXISTS nlink (neighbor_neighbor_id INT, interfaces_intf_id INT, PRIMARY KEY (neighbor_neighbor_id, interfaces_intf_id), CONSTRAINT fk_table1_neighbor1 FOREIGN KEY (neighbor_neighbor_id ) REFERENCES neighbor (neighbor_id) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT fk_table1_interfaces1 FOREIGN KEY (interfaces_intf_id) REFERENCES interfaces (intf_id) ON DELETE CASCADE ON UPDATE CASCADE);
EDIT: SQLITE Version: 3.6.22
After upgrading SQLite to the latest version (3.7.6.2), performance is much better.
After setting an INSERT or DELETE query on QSqlQueryModel, my QTableView becomes screwed up. For example I hid the ID column by calling view->hideColumn(ID); but after an INSERT or DELETE the ID column becomes visible.
How can I automatically reset my view to the previous settings in these cases?
I guess the problem is in QSqlQueryModel::setQuery you're eventually calling every time content gets reloaded and rows inserts\deletes. Looking at the setQuery implementation I would suggest: depending on the query your model can be reset including columns settings change which should trigger view columns update.
As Qt documentation suggests:
The QSqlQueryModel class provides a
read-only data model for SQL result
sets.
so I would use direct QSqlQuery calls for the data updates and then would reload the model with the same query. Or consider switching to QSQLTableModel, which is quite handy for single table content manipulation and supports inserts updates and deletes. See if an example below would work for you:
set up database, view and model:
QSqlTableModel *_model;
QTableView *_view;
...
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName(":memory:");
db.open() ;
QSqlQuery query;
query.prepare("CREATE TABLE IF NOT EXISTS person (id INTEGER UNIQUE PRIMARY KEY, name VARCHAR(30))");
query.exec();
query.prepare("INSERT INTO person (name) VALUES ('test1')");
query.exec();
query.prepare("INSERT INTO person (name) VALUES ('test2')");
query.exec();
_model = new QSqlTableModel(this, db);
_model->setTable("person");
_model->setEditStrategy(QSqlTableModel::OnManualSubmit);
_model->select();
_model->setHeaderData(1, Qt::Horizontal, tr("name"));
_model->setSort(1, Qt::AscendingOrder);
_view = new QTableView(this);
_view->setModel(_model);
_view->hideColumn(0);
add new row:
QSqlRecord record;
_model->insertRecord(-1, record);
delete selected row(s):
QModelIndexList selected = _view->selectionModel()->selectedIndexes();
for (int i = 0; i < selected.size(); ++i)
_model->removeRows(selected.at(i).row(), 1);
submit changes:
_model->submitAll();
hope this helps, regards