#include <QCoreApplication>#include <QtSql/QSqlDatabase>#include <QDebug>#include <QStringList>#include <QSqlError>#include <QSqlQuery>int main(int argc, char *argv[]){
QCoreApplication a(argc, argv);qDebug() << "Available drivers:";
QStringList drivers = QSqlDatabase::drivers();
foreach(QString driver, drivers)
qDebug() << "\t" << driver;
QSqlDatabase db = QSqlDatabase::addDatabase("QODBC");
qDebug() << "ODBC driver valid?" << db.isValid();QSqlDatabase db = QSqlDatabase::addDatabase("QODBC"); // 使用SQL数据库驱动QString servername = "localhost\\SQLEXPRESS";QString dbname = "test";db.setConnectOptions();//QString dsn = QString("DRIVER={SQL SERVER};SERVER=%1;DATABASE=%2;UID=sa,PWD=sa;").arg(servername).arg(dbname);QString dsn = QString("DRIVER={SQL SERVER};SERVER=%1;DATABASE=%2;Trusted_Connection=Yes;").arg(servername).arg(dbname);db.setDatabaseName(dsn);if(!db.open()){qDebug()<<"Unable to open database"<<db.lastError().text();}else{qDebug()<<"Database connection established!";}QSqlQuery qurey(db);bool succes=qurey.exec("SELECT * FROM student");if( succes ){while(qurey.next()){QString sno = qurey.value(0).toString();QString sname = qurey.value(1).toString();qDebug()<<"sno:"<<sno<<"\tsname:"<<sname;}}else{qDebug("^^^db exec is failed");return false;}return a.exec();}
Qt通过ODBC连接SQL_server_2008
最新推荐文章于 2023-08-17 17:35:16 发布