• 3612阅读
  • 0回复

[提问]为啥插入SQL时报错?QSqlQuery::value: not positioned on a valid record [复制链接]

上一主题 下一主题
离线luoqice
 

只看楼主 倒序阅读 楼主  发表于: 2013-03-24
void Widget::on_pushButton_clicked()
{    
QSqlQuery query;
query.prepare("insert into student(id,name)"
              "values(:id,:name)");
query.bindValue(0,5);//id赋值语句
query.bindValue(1,"sixth");//name赋值语句
query.exec();
//下面输出最后一条记录
query.exec("select *form student");


query.last();
int id=query.value(0).toInt();
QString name=query.value(1).toString();
qDebug()<<id<<name;


}


<connection.h>的程序是:


#ifndef CONNECTION_H
#define CONNECTION_H
#include <QMessageBox>
#include <QSqlDatabase>
#include <QSqlQuery>
static bool createConnection()
{
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName(":memory:");
    if (!db.open())
    {
        QMessageBox::critical(0, qApp->tr("Cannot open database"),
            qApp->tr("Unable to establish a database connection."
                     ), QMessageBox::Cancel);
        return false;
    }
    QSqlQuery query;
    query.exec("create table student (id int primary key,"
               "name varchar(20))");//id int primary key 表明id属性是主键
    query.exec("insert into student values(0, 'first')");
    query.exec("insert into student values(1, 'second')");
    query.exec("insert into student values(2, 'third')");
    query.exec("insert into student values(3, 'fourth')");
    query.exec("insert into student values(4, 'fifth')");
    return true;
}
#endif // CONNECTION_H
快速回复
限100 字节
 
上一个 下一个