Qt--- DataBase

a database connection is represented by a QSqlDatabase object and to execute SQL queries, we must first establish a connection with a database.

1 1. bool createConnection()
2 2. {
3 3. QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
4 4. db.setHostName("mozart.konkordia.edu");
5 5. db.setDatabaseName("musicdb");
6 6. db.setUserName("gbatstone");
7 7. db.setPassword("T17aV44");
8 8. if (!db.open()) {
9 9. QMessageBox::critical(0, QObject::tr("Database Error"),
10 10. db.lastError().text());
11 11. return false;
12 12. }
13 13. return true;
14 14. }

if open() fails, we show an error message.


Once a connection is established, we can use QSqlQuery to execute any SQL statement that the underlying database supports

1 1. QSqlQuery query;
2 2. query.exec("SELECT title, year FROM cd WHERE year >= 1998");

We call next() once to position the QSqlQuery on the first record of the result set

if the result set is empty , the frist call to next() will return false

当然我们并不是所以内容都希望转换为string 类型的,而 prepare() 可以使用户使用指定的类型的变量,如果我们希望create multiple cconnections, we can pass a name as second argument to   addDatabase()

QSqlDatabase::addDatabase("QPSQL","OTHER");

posted @ 2010-12-07 13:10  崖山.  阅读(380)  评论(0)    收藏  举报