正在学习用qt做一个qq的登陆界面,遇到了下面这个问题,我在数据库中只存了两个id,但是当我输入错误的id的时候,query.prepare返回值用debug打出依然是true,是哪里出了问题吗,还有就是数据库表只能创建一次吗,我多次创建为什么提示我创建失败啊,搞了一下午,头疼啊。
bool value;
QString username=ui->lusername->text(); //获取输入的id
QString passwd=ui->lpasswd->text(); //获取输入的密码
value=query.prepare("SELECT id,passwd FROM account WHERE id=:id"); //查询数据库表account中id是否存在,有则返回true,没有则返回false。
query.bindValue(":id",username);
query.exec();
qDebug()<<value;//打印返回值
下面是我的main.cpp程序:
#include
#include"lanqq.h"
#include
#include
#include
#include
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
// lanqq w;
QSqlDatabase db=QSqlDatabase::addDatabase("QSQLITE");
db.setHostName("localhost");
db.setDatabaseName("qtDb.db");
db.setUserName("root");
db.setPassword("123456");
if(db.open()==false)
{
qDebug("open db error");
}
qDebug("open db sucessful");
QSqlQuery query;
bool sucess=query.exec("create table account(id varchar(20) primary key,passwd varchar(20)");
if(sucess==false)
{
qDebug()<<QObject::tr("table estaiblish failed");
}
query.prepare("INSERT INTO account(id,passwd) VALUES(:id,:passwd)");
query.bindValue(":id","naruto");
query.bindValue(":passwd","1234567");
query.prepare("INSERT INTO account(id,passwd) VALUES(:id,:passwd)");
query.bindValue(":id","nihao");
query.bindValue(":passwd","123456");
query.exec();
if(query.first())
{
QString passwd1=query.value(0).toString(); //这里也不能打印,不知什么情况
qDebug()<<passwd1;
}
lanqq w;
w.show();
return a.exec();
}
多次创建同一数据库表,当然会报错了