日期:2014-05-16  浏览次数:20739 次

Qt相关mysql操作及时间日期(一)

         文章先介绍Qt操作MySQL的一些基本语句,后面有MySQL数据库文件信息、时间日期函数的一些介绍

打开数据库

    //QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
      //db.setDatabaseName(":memory:");

打开SQLite简单,打开MYSQL就麻烦点

    QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");

    db.setHostName("localhost");
    db.setDatabaseName("test");
    
    //db.setDataBaseName("");
    db.setUserName("root");
    db.setPassword("000000");

    if (!db.open())
        return db.lastError();
    qDebug()<<QString("open database");

创建数据表

//q.exec("DROP TABLE books");
    if (!q.exec(QLatin1String("CREATE TABLE books(id INTEGER PRIMARY KEY AUTO_INCREMENT, title VARCHAR(40), author INTEGER, genre INTEGER, year INTEGER, rating INTEGER)")))
        return q.lastError();

遍历操作

      QSqlQuery q;

     q.exec(SELECT title,year FROM cd WHERE year >=2012);

    while(q.next()){

    QDateTime temp= q.value(0).toDateTime();

   int id=q.value(1).toInt();

   }

插入操作

    if (!q.prepare(QLatin1String("insert into books(title, year, author, genre, rating) values(?, ?, ?, ?, ?)")))
        return q.lastError();
    addBook(q, QLatin1String("Foundation"), 1951, asimovId, sfiction, 3);
    addBook(q, QLatin1String("Foundation and Empire"), 1952, asimovId, sfiction, 4);
    addBook(q, QLatin1String("Second Foundation"), 1953, asimovId, sfiction, 3);

绑定插入参数,

如果 是属性含有default,并且想按照默认值插入数据的话,就insert中不插入该项;

如果属性为AUTO_INCREMENT,插入的时候会自动生成

void addBook(QSqlQuery &q, const QString &title, int year, const QVariant &authorId,
             const QVariant &genreId, int rating)
{
    q.addBindValue(title);
    q.addBindValue(year);
    q.addBindValue(authorId);
    q.addBindValue(genreId);
    q.addBindValue(rating);
    q.exec();
}

利用QSqlTableModel高级界面操作接口,请参考《C++ GUI Qt4编程(第二版)》241页,讲的很详细!多读有益!

QSqlTableModel model;

model.setTable("testTable");

model.setFilter("age >= 60");

model.select();

下面给出一个不完整但很有用的书13章的例子,本人做了些修改,删除部门表中的记录,该例子中用到数据库事务处理、SQL语句的执行,另外还有对话框的使用

void MainForm::deleteDepartment()
{
    QModelIndex index = departmentView->currentIndex();
    if(!index.isValid())
        return;
    QSqlDatabase::database().transaction();
    QSqlRecord record = departmentModel->record(index.row());
    int id = record.va