天朝皇叔:学习笔记 Qt 连接数据库sql server

本文介绍了如何在Qt项目中连接到SQL Server数据库,重点讨论了通过ODBC驱动的连接字符串及其不同形式,包括DSN、文件DSN和直接连接字符串。同时,详细解释了SQLDriverConnect函数的工作原理及注意事项,确保在不同连接方式下正确设置用户认证和数据源。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在项目文件里面加上:QT       += sql

注意连接字符串的多种方式:直接填连接字符串;字符串与函数调用拼接、使用数据源,示例代码:

​
#include <QtCore/QCoreApplication>
#include <QtSql>
#include <QStringList>
#include <QSqlQuery>
#include <QDebug>

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    //qDebug() << "Available drivers:";

 //测试QT系统当前安装的驱动
    QStringList drivers = QSqlDatabase::drivers();
    foreach(QString driver, drivers)
    qDebug() << "\t" << driver;
    QSqlDatabase db = QSqlDatabase::addDatabase("QODBC");
    qDebug() << "ODBC driver valid?" << db.isValid();

    //连接方式1 完全使用链接字符串 不用配置数据源
   QString dsn = QString::fromLocal8Bit("DRIVER={SQL SERVER};SERVER=192.168.1.42;Uid=sa;Pwd=woaini;DATABASE=Northwind");
  db.setDatabaseName(dsn);

  //连接方式2 使用链接字符串 拼接
    //QString dsn = QString::fromLocal8Bit("DRIVER={SQL SERVER};SERVER=192.168.1.42;DATABASE=Northwind");
    //db.setDatabaseName(dsn);
    // db.setUserName("sa");
    // db.setPassword("woaini");

    // 3.使用数据源 zfgdb是系统配置的sql server ODBC数据源名称,密码在数据源已保存
    // db.setDatabaseName("zfgdb");//zfgdb是系统配置的sql server  ODBC数据源名称
      
  //4 连接 Access数据库
//      //db.setDatabaseName("DRIVER={Microsoft Access Driver (*.mdb)};FIL={MS Access};DBQ=myaccessfile.mdb");
//       db.setDatabaseName(dsn);

    if(db.open()){
        qDebug() <<"hostname:"<<db.hostName();
        QSqlQuery query;
        query.exec("select * from Region");
        while (query.next()) {
            qDebug() << "\t"<< query.value(1).toString();

        }
    }
    else
        qDebug() << "Database not opened!";

    return a.exec();
}



​

 数据源选默认数据库:

 通过ODBC数据库驱动的链接字符串, 见 sql server 联机文档关于  SQLDriverConnect 的描述(附后)
  Qt 最后都是调用了微软的驱动程序

  //Qt 关于关于连接字符串,见Qt 文档:
 void QSqlDatabase::setDatabaseName ( const QString & name ):

For the QOCI (Oracle) driver, the database name is the TNS Service Name.

For the QODBC driver, the name can either be:
1.   a DSN,
2.  a DSN filename (in which case the file must have a .dsn extension),
3.  or a connection string.

For example, Microsoft Access users can use the following connection string to open an .mdb file directly,
instead of having to create a DSN entry in the ODBC manager:

...
db = QSqlDatabase::addDatabase("QODBC");
db.setDatabaseName("DRIVER={Microsoft Access Driver (*.mdb)};FIL={MS Access};DBQ=myaccessfile.mdb");
if (db.open()) {
 // success!

看几个重要函数源代码,就会明白链接字符串的意义:

bool QSqlDatabase::open()
{
    return d->driver->open(d->dbname, d->uname, d->pword, d->hname,
                            d->port, d->connOptions);
}

}

bool QODBCDriver::open(const QString & db,
                        const QString & user,
                        const QString & password,
                        const QString &,
                        int,
                        const QString& connOpts)
{
    if (isOpen())
      close();
    SQLRETURN r;
    //....
    // Create the connection string  生成连接字符串
    QString connQStr;
    // support the "DRIVER={SQL SERVER};SERVER=blah" syntax
    if (db.contains(QLatin1String(".dsn"), Qt::CaseInsensitive))
        connQStr = QLatin1String("FILEDSN=") + db;
    else if (db.contains(QLatin1String("DRIVER="), Qt::CaseInsensitive)
            || db.contains(QLatin1String("SERVER="), Qt::CaseInsensitive))
        connQStr = db;
    else
        connQStr = QLatin1String("DSN=") + db;

    if (!user.isEmpty())
        connQStr += QLatin1String(";UID=") + user;
    if (!password.isEmpty())
        connQStr += QLatin1String(";PWD=") + password;

    SQLSMALLINT cb;
    QVarLengthArray<SQLTCHAR> connOut(1024);
    memset(connOut.data(), 0, connOut.size() * sizeof(SQLTCHAR));
    r = SQLDriverConnect(d->hDbc,
                          NULL,
                          toSQLTCHAR(connQStr).data(),
                          (SQLSMALLINT)connQStr.length(),
                          connOut.data(),
                          1024,
                          &cb,
                        0);   //  SQL_DRIVER_NOPROMPT  

   //....错误处理
    //    return true;
}

 

 

  本人实际的代码:

通过ODBC数据库驱动的链接字符串, 见 sql server 联机文档关于  SQLDriverConnect 的描述

SQLDriverConnect

The Microsoft® SQL Server™ ODBC driver and the ODBC driver manager recognize the following SQLDriverConnect connection string keywords.

Keyword

Description

Address

Network address of the server running an instance of SQL Server. Address is usually the network name of the server, but can be other names such as a pipe, or a TCP/IP port and socket address. For more information, see Managing Clients.

AnsiNPW

When yes, the driver uses ANSI-defined behaviors for handling NULL comparisons, character data padding, warnings, and NULL concatenation. When no

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值