How it works…

It's very important to check whether the database is connected before we proceed to send a SQL query to the database. Therefore, we keep that status in a variable and use it to check before sending out any queries. This, however, is not recommended for complex programs that are kept open for long periods of time, as the database might get disconnected during those periods, and a fixed variable may not be accurate. In that case, it's better to check the actual status by calling QSqlDatabase::isOpen().

The currentID variable is used to save the ID of the current data you obtained from the database. When you want to update the data or delete it from the database, this variable is crucial for letting the database know what data you're trying to update or delete. If you set your database table correctly, MySQL will treat each item of data as a unique entry, so you can be sure that no repeated ID will be produced in the database when new data is being saved.

After inserting new data into the database, we call QSqlQuery::lastInsertId() to obtain the ID of the new data and save it as a currentID variable so that it becomes the current data that we can update or delete from the database. It is a good habit to test your SQL queries on phpMyAdmin before using them in Qt. You can instantly find out whether your SQL statements are correct or incorrect, instead of waiting for your project to be built, trying it out, then rebuilding it. As programmers, we must work in the most efficient way. Work hard, and work smart.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset