#include <QApplication>
#include<QSql>
#include <QDialog>
#include <QDebug>
#include <QMessageBox>
#include<QSqlError>
#include<QSqlDatabase>
#include<QSqlQuery>
bool OpenDatabase()
{
QSqlDatabase db = QSqlDatabase::addDatabase("QODBC"); //数据库驱动类型为SQL Server
qDebug()<<"ODBC driver?"<<db.isValid();
QString dsn = QString::fromLocal8Bit("sql"); //数据源名称
db.setHostName("localhost"); //选择本地主机,127.0.1.1
db.setDatabaseName(dsn); //设置数据源名称
db.setUserName("sa"); //登录用户
db.setPassword("123"); //密码
if(!db.open()) //打开数据库
{
qDebug()<<db.lastError().text();
QMessageBox::critical(0, QObject::tr("Database error"), db.lastError().text());
return false; //打开失败
}
else
{
qDebug()<<"database open success!";这句话在输出中会显示出来
}return true;
}
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
if(!OpenDatabase())
return 1;
//以下执行相关sql语句
QSqlQuery query;
query.exec("select recovery from retemp where username == 2");
//query.next()指向查找到的第一条记录,然后每次后移一条记录
while(query.next())
{
//query.value(0)是id的值,将其转换为int型
int value0 = query.value(0).toInt();
//QString value1 = query.value(1).toString();
//输出两个值
qDebug() << value0 ;
}
w.show();
return a.exec();
}
2 个解决方案
#1
query.exec有没有返回错误码 ?
#2
ODBC driver? true
[LspTrace]process path is D:\qt\qtexample\build-loginin-Desktop_Qt_5_11_1_MinGW_32bit-Debug\debug\loginin.exe
[LspTrace]ReadAccConfig returns false!
[LspTrace]FindMatchingProvider: inInfo is one of the LSPs entry.
[LspTrace]WSPStartup end: 0, protocol=17
[LspTrace]FindMatchingProvider: inInfo is one of the LSPs entry.
[LspTrace]WSPStartup end: 0, protocol=6
database open success!
这个是所有的返回代码
[LspTrace]process path is D:\qt\qtexample\build-loginin-Desktop_Qt_5_11_1_MinGW_32bit-Debug\debug\loginin.exe
[LspTrace]ReadAccConfig returns false!
[LspTrace]FindMatchingProvider: inInfo is one of the LSPs entry.
[LspTrace]WSPStartup end: 0, protocol=17
[LspTrace]FindMatchingProvider: inInfo is one of the LSPs entry.
[LspTrace]WSPStartup end: 0, protocol=6
database open success!
这个是所有的返回代码
#1
query.exec有没有返回错误码 ?
#2
ODBC driver? true
[LspTrace]process path is D:\qt\qtexample\build-loginin-Desktop_Qt_5_11_1_MinGW_32bit-Debug\debug\loginin.exe
[LspTrace]ReadAccConfig returns false!
[LspTrace]FindMatchingProvider: inInfo is one of the LSPs entry.
[LspTrace]WSPStartup end: 0, protocol=17
[LspTrace]FindMatchingProvider: inInfo is one of the LSPs entry.
[LspTrace]WSPStartup end: 0, protocol=6
database open success!
这个是所有的返回代码
[LspTrace]process path is D:\qt\qtexample\build-loginin-Desktop_Qt_5_11_1_MinGW_32bit-Debug\debug\loginin.exe
[LspTrace]ReadAccConfig returns false!
[LspTrace]FindMatchingProvider: inInfo is one of the LSPs entry.
[LspTrace]WSPStartup end: 0, protocol=17
[LspTrace]FindMatchingProvider: inInfo is one of the LSPs entry.
[LspTrace]WSPStartup end: 0, protocol=6
database open success!
这个是所有的返回代码