QSqlTableModel class operation database (create, query, delete, modify) detailed explanation

Introduction

Read all data in the table

QSqlTableModel can only cache up to 256 query results at a time. That is, if the result of the filter select operation exceeds 256, rowCount can only return 256.

	QSqlTableModel model;
	MonitorPointsC mpc;
	model.setTable(MONITORTABLENAME);//设置表
	model.setFilter("");		     //选择表
	model.select();
	//在操作结果前先通过fetchmore()来获取所有的结果
	while (model.canFetchMore())
	{
    
    
		model.fetchMore();
	}

	addMessage("", QStringLiteral("%1").arg(model.rowCount()));

Update a column of data in the table

Here, QSqlTableModel is used to operate the database. For a large amount of data, there is a huge gap in performance compared with QSqlQuery. In order to improve performance, the use of db.transaction(); and db.commit(); can make the performance of the two close.


	db.transaction();
	for (int i = 0; i < model.rowCount(); ++i)
	{
    
    
		QSqlRecord record = model.record(i);
		QString temp = record.value(mpc.CurrentTime).toString();

		if (temp.indexOf(" 00:00:00") == -1)
		{
    
    
			continue;
		}

		temp = temp.replace(" 00:00:00", "");
		record.setValue(mpc.CurrentTime, temp);
		model.setRecord(i, record);
		if (model.submitAll()){
    
    
			//addMessage("", QStringLiteral("%1").arg("succ"));
		}
		else{
    
    
			//addMessage("", QStringLiteral("%1").arg("fail"));
		}
	}
	//addMessage("", QStringLiteral("%1").arg("成功"));
	db.commit();
	

About transaction() and commit() introduction

Qt recommends the use of transactions when operating large amounts of data to perform insert operations

1. SQLite database is essentially a file on disk, so all database operations will actually be converted to file operations, and frequent file operations will be a very timely process, which will greatly affect database access speed. For example: insert 1 million pieces of data into the database, by default, if you just execute query.exec("insert into DataBase(...) values(...)"); the file will be opened and closed 1 million times, So of course the speed will be very slow.

2. The SQLite database supports transaction operations, so we can improve the read and write speed of the database through transactions. The basic principle of the transaction is: the database management system will first store the SQL statement to be executed in the memory, and only execute all the databases in the memory at one time when commit().

No affairs

If you don't need a transaction, insert 1000 pieces of data into the sqlite database, and execute 1000 times to start and end the transaction.

The general method of using transactions in Qt:

db.transaction(); 
执行插入的sql(n条插入操作) 
db.commit();

or

QSqlDatabase::database().transaction(); 
执行插入的sql(n条插入操作) 
QSqlDatabase::database().commit();

Reference: https://blog.csdn.net/rl529014/article/details/79451381

Guess you like

Origin blog.csdn.net/wokaowokaowokao12345/article/details/106710484