在Project.pro文件中,我们添加:CONFIG += sql
在MainWindow.h我们写道:
#include <QMainWindow> #include <QSql> #include <QDebug> namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = 0); ~MainWindow(); private slots: private: Ui::MainWindow *ui; QSqlDatabase db; };
现在在MainWindow.cpp:
#include "mainwindow.h" #include "ui_mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); db = QSqlDatabase::addDatabase("QODBC" , "CONNECTION NAME"); db.setDatabaseName("DRIVER={SQL Server};SERVER=localhost;DATABASE=WorkDatabase"); // "WorkDatabase" is the name of the database we want db.setUserName("sa"); // 设置登录用户名 db.setPassword(""); // 根据需要设置密码 if(!db.open()) { qDebug() << "Can't Connect to DB !"; } else { qDebug() << "已成功连接到数据库!"; QSqlQuery query; query.prepare("SELECT name , phone , address FROM employees WHERE ID = 201"); if(!query.exec()) { qDebug() << "Can't Execute Query !"; } else { qDebug() << "查询执行成功!"; while(query.next()) { qDebug() << "员工姓名 : " << query.value(0).toString(); qDebug() << "员工电话: " << query.value(1).toString(); qDebug() << "员工地址: " << query.value(1).toString(); } } } } MainWindow::~MainWindow() { delete ui; }