应用程序很多情况下需要操作数据库。QT支持多种数据库,但是很多情况需要安装DLL驱动。这就有点麻烦,想当初想用MYSQL的结果就


是因为驱动很难装,然后就使用了SQLITE。如果对数据库的要求不是很高的话,Sqlite应该可以满足需求了。下面就简单介绍下在QT中的


点击(此处)折叠或打开

  1. 需要包含如下的数据库相关头文件:
  2. #include <QSqlDatabase>
  3. #include <QSqlQuery>

点击(此处)折叠或打开

  1. 下面是创建数据库的操作,写成 createConnection()
  2. bool database::createconnection()
  3. {
  4.     bool IsExist = QFile::exists("Myqq.dat");
  5.     db = QSqlDatabase::addDatabase("QSQLITE"); // 注意不要拼写错误
  6.     db.setDatabaseName("Myqq.dat");
  7.     if (!db.open())
  8.     {
  9.         QMessageBox::critical(0, "Cannot open database",
  10.             "Unable to establish a database connection./n"
  11.                      "This example needs SQLite support. Please read "
  12.                      "the Qt SQL driver documentation for information how "
  13.                      "to build it./n/n"
  14.                      "Click Cancel to exit.", QMessageBox::Cancel);
  15.         return false;
  16.     }
  17.     if (!IsExist)
  18.     {
  19.         if (!createDatabase())
  20.             return false;
  21.     }
  22.     return true;
  23. }


点击(此处)折叠或打开

  1. 下面是创建数据库的操作,写成 createConnection()
  2. bool database::createconnection()
  3. {
  4.     bool IsExist = QFile::exists("Myqq.dat");
  5.     db = QSqlDatabase::addDatabase("QSQLITE"); // 注意不要拼写错误
  6.     db.setDatabaseName("Myqq.dat");
  7.     if (!db.open())
  8.     {
  9.         QMessageBox::critical(0, "Cannot open database",
  10.             "Unable to establish a database connection./n"
  11.                      "This example needs SQLite support. Please read "
  12.                      "the Qt SQL driver documentation for information how "
  13.                      "to build it./n/n"
  14.                      "Click Cancel to exit.", QMessageBox::Cancel);
  15.         return false;
  16.     }
  17.     if (!IsExist)
  18.     {
  19.         if (!createDatabase())
  20.             return false;
  21.     }
  22.     return true;
  23. }


点击(此处)折叠或打开

  1. 下面是创建数据库 createDatabase()。创建了两张表,最需要注意的就是:不要把数据库操作写错了,比如单词写错了。因为没有提示,所以还是蛮容易写错的。最后出错了,还不容易找到错误。
  2. bool database::createDatabase()
  3. {
  4.     QSqlQuery query;
  5.     qDebug() << "Start to create table..."; // qDebut()方便在 debug 的时候查看
  6.     //create table: User
  7.     query.exec("CREATE TABLE [User] ( [userId] VARCHAR(40) NOT NULL, [username] VARCHAR(40) NOT NULL, [email] VARCHAR(40), [password] VARCHAR(40), [city] VARCHAR(20), PRIMARY KEY([userId]) )");
  8.     //create table: Connect
  9.     query.exec("CREATE TABLE [Connect] ( [LeftUser] VARCHAR(40) NOT NULL, [RightUser] VARCHAR(40) NOT NULL, [relation] INTEGER DEFAULT '0' NULL, PRIMARY KEY ([LeftUser], [RightUser]))");
  10.     if (query.lastError().isValid())
  11.     {
  12.         qDebug() << query.lastError();
  13.         return false;
  14.     }
  15.     else
  16.     {
  17.         qDebug() << "Create database successfully.";
  18.     }
  19.     return true;
  20. }
下面就简单的贴下自己写的 创建和插入的操作方法。会写数据库的童鞋知道语法了 就知道怎么写了


点击(此处)折叠或打开

  1. bool database::createDatabase()
  2. {
  3.     QSqlQuery query; // 此处请查询 query的相关操作
  4.     qDebug() << "Start to create table...";
  5.     //create table: User
  6.     query.exec("CREATE TABLE [User] ( [userId] VARCHAR(40) NOT NULL, [username] VARCHAR(40) NOT NULL, [email] VARCHAR(40), [password] VARCHAR(40), [city] VARCHAR(20), PRIMARY KEY([userId]) )"); // 一定注意不要拼写错误,引号内是不提示拼写错误的。自己也感觉这有点不方便
  7.     //create table: Connect
  8.     query.exec("CREATE TABLE [Connect] ( [LeftUser] VARCHAR(40) NOT NULL, [RightUser] VARCHAR(40) NOT NULL, [relation] INTEGER DEFAULT '0' NULL, PRIMARY KEY ([LeftUser], [RightUser]))");
  9.     if (query.lastError().isValid())
  10.     {
  11.         qDebug() << query.lastError();
  12.         return false;
  13.     }
  14.     else
  15.     {
  16.         qDebug() << "Create database successfully.";
  17.     }
  18.     return true;
  19. }

插入操作


点击(此处)折叠或打开

  1. bool database::adduser( User user )
  2. {
  3.     if (!db.isOpen())
  4.     {
  5.         createconnection();
  6.     }
  7.     QSqlQuery query;
  8.     qDebug() << "start to insert data";
  9.     query.exec("INSERT INTO [User] ( userId, username, email, password, city) VALUES(?,?,?,?,?)");
  10.     QVariantList userId;
  11.     userId << user.getUserId();
  12.     query.addBindValue(userId);
  13.     QVariantList username;
  14.     username << user.getUserName();
  15.     query.addBindValue(username);
  16.     QVariantList email;
  17.     email << user.getEmail();
  18.     query.addBindValue(email);
  19.     QVariantList password;
  20.     password << user.getPassword();
  21.     query.addBindValue(password);
  22.     QVariantList city;
  23.     city << user.getCity();
  24.     query.addBindValue(city);
  25.     try
  26.     {
  27.         if (!query.execBatch())
  28.         {
  29.             qDebug() << query.lastQuery();
  30.             qDebug() << query.lastError();
  31.             return NULL;
  32.         }
  33.     }
  34.     catch(...)
  35.     {
  36.         QMessageBox::critical(0, "Add New Node error!",
  37.                               "Unable to add a new Node!/n/n"
  38.                                        "Click Cancel to exit.", QMessageBox::Cancel);
  39.     }
  40.     if( !UpdateConnectTable(user.getUserId(),user.getUserId(),2))
  41.     {
  42.         QMessageBox::critical(0,"","Update table Connect error");
  43.         return NULL;
  44.     }
  45.     return true;
  46. }




09-03 11:17