在项目文件里面加上: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();}}elseqDebug() << "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" syntaxif (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;elseconnQStr = 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, ANSI defined behaviors are not exposed. For more information about ANSI NPW behaviors, see Effects of SQL-92 Options.

APP

Name of the application calling SQLDriverConnect (optional). If specified, this value is stored in the master.dbo.sysprocesses column program_name and is returned by sp_who and the Transact-SQL APP_NAME function.

AttachDBFileName

Name of the primary file of an attachable database. Include the full path and escape any \ characters if using a C character string variable:

AttachDBFileName=c:\\MyFolder\\MyDB.mdf

This database is attached and becomes the default database for the connection. To use AttachDBFileName you must also specify the database name in either the SQLDriverConnnect DATABASE parameter or the SQL_COPT_CURRENT_CATALOG connection attribute. If the database was previously attached, SQL Server will not reattach it; it will use the attached database as the default for the connection.

AutoTranslate

When yes, ANSI character strings sent between the client and server are translated by converting through Unicode to minimize problems in matching extended characters between the code pages on the client and the server:

Client SQL_C_CHAR data sent to a SQL Server char, varchar, or text variable, parameter, or column is converted from character to Unicode using the client ANSI code page (ACP), then converted from Unicode to character using the ACP of the server.

SQL Server char, varchar, or text data sent to a client SQL_C_CHAR variable is converted from character to Unicode using the server ACP, then converted from Unicode to character using the client ACP.

These conversions are performed on the client by the SQL Server ODBC driver. This requires that the same ANSI code page (ACP) used on the server be available on the client.

These settings have no effect on the conversions that occur for these transfers:

Unicode SQL_C_WCHAR client data sent to char, varchar, or text on the server.

char, varchar, or text server data sent to a Unicode SQL_C_WCHAR variable on the client.

ANSI SQL_C_CHAR client data sent to Unicode nchar, nvarchar, or ntext on the server.

Unicode char, varchar, or text server data sent to an ANSI SQL_C_CHAR variable on the client.

When no, character translation is not performed.

The SQL Server ODBC driver does not translate client ANSI character SQL_C_CHAR data sent to char, varchar, or text variables, parameters, or columns on the server. No translation is performed on char, varchar, or text data sent from the server to SQL_C_CHAR variables on the client.

If the client and SQL Server are using different ACPs, then extended characters can be misinterpreted.

DATABASE

Name of the default SQL Server database for the connection. If Database is not specified, the default database defined for the login is used. The default database from the ODBC data source overrides the default database defined for the login. The database must be an existing database unless AttachDBFileName is also specified. If AttachDBFileName is also specified, the primary file it points to is attached and given the database name specified by DATABASE.

DRIVER

Name of the driver as returned by SQLDrivers. The keyword value for the SQL Server ODBC driver is "{SQL Server}". The braces are required when using version 2.65 or earlier of the SQL Server ODBC driver. The SERVER keyword is required if DRIVER is specified and DriverCompletion is set to SQL_DRIVER_NOPROMPT.

DSN

Name of an existing ODBC user or system data source.

Fallback
(SQL Server 6.5 only)

When yes, instructs the driver to attempt connection to a fallback server if connection to a primary server fails. The login time-out (set with ODBC SQLSetConnectAttr, attribute SQL_ATTR_LOGIN_TIMEOUT) must be set for fallback to occur. When no, no attempt at a fallback connection is made. This option applies only to standby servers. It does not apply to a virtual server in a cluster/failover configuration.

FILEDSN

Name of an existing ODBC file data source.

LANGUAGE

SQL Server language name (optional). SQL Server can store messages for multiple languages in sysmessages. If connecting to a SQL Server with multiple languages, Language specifies which set of messages are used for the connection.

Network

Name of a network library dynamic-link library. The name need not include the path and must not include the .dll file name extension, for example, Network=dbnmpntw.

PWD

The password for the SQL Server login account specified in the UID parameter. PWD need not be specified if the login has a NULL password or when using Windows Authentication (Trusted_Connection = yes).

SAVEFILE

Name of an ODBC data source file into which the attributes of the current connection are saved if the connection is successful.

SERVER

Name of a server running SQL Server on the network. The value must be either the name of a server on the network, or the name of a SQL Server Client Network Utility advanced server entry. You can enter (local) as the server name on Microsoft Windows® NT 4.0 to connect to a copy of SQL Server running on the same computer. SQL Server 2000 supports multiple instances of SQL Server running on the same computer. To specify a named instance of SQL Server, the server name is specified as ServerName\InstanceName. For more information about server names, see Managing Clients.

QueryLogFile

Full path and file name of a file to use to log data on long-running queries.

QueryLog_On

When yes, logging long-running query data is enabled on the connection. When no, long-running query data is not logged.

QueryLogTime

Digit character string specifying the threshold (in milliseconds) for logging long-running queries. Any query that does not get a response in the time specified is written to the long-running query log file.

QuotedID

When yes, QUOTED_IDENTIFIERS is set ON for the connection, SQL Server uses the SQL-92 rules regarding the use of quotation marks in SQL statements. When no, QUOTED_IDENTIFIERS is set OFF for the connection. SQL Server then follows the legacy Transact-SQL rules regarding the use of quotation marks in SQL statements. For more information, see Effects of SQL-92 Options.

Regional

When yes, the SQL Server ODBC driver uses client settings when converting currency, date, and time data to character data. The conversion is one way only; the driver does not recognize non-ODBC standard formats for date strings or currency values within; for example, a parameter used in an INSERT or UPDATE statement. When no, the driver uses ODBC standard strings to represent currency, date, and time data that is converted to string data.

StatsLogFile

Full path and file name of a file used to record SQL Server ODBC driver performance statistics.

StatsLog_On

When yes, enables the capture of SQL Server ODBC driver performance data. When no, SQL Server ODBC driver performance data is not available on the connection.

Trusted_Connection

When yes, instructs the SQL Server ODBC driver to use Windows Authentication Mode for login validation. The UID and PWD keywords are optional. When no, instructs the SQL Server ODBC driver to use a SQL Server username and password for login validation. The UID and PWD keywords must be specified.

UID

A valid SQL Server login account. UID need not be specified when using Windows Authentication.

UseProcForPrepare
(SQL Server 6.5 and earlier only)

When 1, instructs the SQL Server ODBC driver to create temporary stored procedures when statements are prepared with SQLPrepare. The temporary stored procedures are not dropped until the connection is broken.

When 2, the SQL Server ODBC driver creates temporary stored procedures for SQLPrepare, but only one procedure is created per statement handle and the procedure is dropped when the statement handle becomes invalid or a new SQL statement is prepared. When 0, the SQL Server ODBC driver does not create temporary stored procedures for SQLPrepare.

WSID

Workstation ID. Typically, this is the network name of the computer on which the application resides (optional). If specified, this value is stored in the master.dbo.sysprocesses column hostname and is returned by sp_who and the Transact-SQL HOST_NAME function.

Note  Regional conversion settings apply to currency, numeric, date, and time data types. The conversion setting is only applicable to output conversion and is only visible when currency, numeric, date, or time values are converted to character strings.

The driver uses the locale registry settings for the current user. The driver does not honor the current thread's locale if the application sets it after connection by, for example, calling SetThreadLocale.

Altering the regional behavior of a data source can cause application failure. An application that parses date strings, and expects date strings to appear as defined by ODBC, could be adversely affected by altering this value.

The SQL Server ODBC driver defines connection attributes that either replace or enhance connection-string keywords. Several connection-string keywords have default values specified by the SQL Server ODBC driver. For more information about SQL Server connection attributes and driver default behaviors, see SQLSetConnectAttr.

When the SQLDriverConnect DriverCompletionparameter value is SQL_DRIVER_PROMPT, SQL_DRIVER_COMPLETE, or SQL_DRIVER_COMPLETE_REQUIRED, the SQL Server ODBC driver retrieves keyword values from the displayed dialog box. If the keyword value is passed in the connection string and the user does not alter the value for the keyword in the dialog box, the SQL Server ODBC driver uses the value from the connection string. If the value is not set in the connection string and the user makes no assignment in the dialog box, the driver uses the default.

SQLDriverConnect must be given a valid WindowHandle when any DriverCompletion value requires (or could require) the display of the driver's connection dialog box. An invalid handle returns SQL_ERROR.

Specify either the DRIVER or DSN keywords. ODBC states that a driver uses the leftmost of these two keywords and ignores the other if both are specified. If DRIVER is specified, or is the leftmost of the two, and the SQLDriverConnect DriverCompletion parameter value is SQL_DRIVER_NOPROMPT, the SERVER keyword and an appropriate value are required.

When SQL_DRIVER_NOPROMPT is specified, user authentication keywords must be present with values. The driver ensures that either the string "Trusted_Connection=yes" or both the UID and PWD keywords are present.

If the DriverCompletion parameter value is SQL_DRIVER_NOPROMPT or SQL_DRIVER_COMPLETE_REQUIRED and the language or database comes from the connection string and either is invalid, SQLDriverConnect returns SQL_ERROR.

If the DriverCompletion parameter value is SQL_DRIVER_NOPROMPT or SQL_DRIVER_COMPLETE_REQUIRED and the language or database comes from the ODBC data source definitions and either is invalid, SQLDriverConnect uses the default language or database for the specified user ID and returns SQL_SUCCESS_WITH_INFO.

If the DriverCompletion parameter value is SQL_DRIVER_COMPLETE or SQL_DRIVER_PROMPT and if the language or database is invalid, SQLDriverConnect redisplays the dialog box.

Examples

The following call illustrates the least amount of data required for SQLDriverConnect:

SQLDriverConnect(hdbc, hwnd,

(SQLTCHAR*) "DRIVER={SQL Server};" SQL_NTS, szOutConn,

MAX_CONN_OUT, cbOutConn, SQL_DRIVER_COMPLETE);

The following connection strings illustrate minimum required data when the DriverCompletion parameter value is SQL_DRIVER_NOPROMPT:

"DSN=Human Resources;UID=Smith;PWD=Sesame"

"DSN=Human Resources;Trusted_Connection=yes"

"FILEDSN=HR_FDSN;UID=Smith;PWD=Sesame"

"FILEDSN=HR_FDSN;Trusted_Connection=yes"

"DRIVER={SQL Server};SERVER=hrserver;UID=Smith;PWD=Sesame"

"DRIVER={SQL Server};SERVER=hrserver;Trusted_Connection=yes"

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

  1. mySql学习笔记:比sql server书写要简单

    在学mySql.总的感觉,mySql与Sql Server差不多,语法都很象,但mySql也许是吸取了SQL SERVER的一些经验,SQL语句书写起来更加简单. 比如说,设置主键.索引,SQL SE ...

  2. python读取sqlserver数据库方法_SQLServer数据库之Python读取配置文件,并连接数据库SQL Server...

    本文主要向大家介绍了SQLServer数据库之Python读取配置文件,并连接数据库SQL Server,通过具体的内容向大家展现,希望对大家学习SQLServer数据库有所帮助. 用配置文件保存固定 ...

  3. Qt连接SQL Server 2014数据库

    Qt连接SQL Server 2014数据库 1. 建立目标数据库 连接数据库之前,需先在SQL Server中建立一个目标数据库,建立数据库和添加表的步骤这里不详述. 如建立一个名为DataBase ...

  4. 【数据库学习笔记】Day03 - SQL语言基础及数据库定义功能

    [数据库学习笔记]Day03 - SQL语言基础及数据库定义功能 〇.本文所用数据库表格: 一.关系运算: 关系运算,数学名词,基本运算有两类:一类是传统的集合运算(并.差.交等),另一类是专门的关系 ...

  5. QT连接SQL server 数据库

    Qt连接SQL server数据库 由于课程设计需要,需要用qt设计一个界面来操作数据库,在建立数据库连接时,期间遇到各种问题. Qt 连接SQL server数据大致可以概括为下图的三层模型,箭头代 ...

  6. qt 连接SQL Server服务器

    qt连接sql server 需要配置ODBC数据源 一.数据源配置 控制面板 → 管理工具 → ODBC 数据源 数据源名称自起(等会儿代码中会用到). 服务器输入要连接服务器名称. 录入登录名,密 ...

  7. 【白帽子学习笔记14】SQL注入常用语句

    [白帽子学习笔记14]SQL注入常用语句 目前网站中使用的最多的数据库要算是 ACCESS.SQL Server(MSSQL).MySQL 这三个了,所以这里的手工注入,我就以他们三个数据库来分成三 ...

  8. MySQL学习笔记02【SQL基本概念与通用语法、数据库的CRUD操作】

    MySQL 文档-黑马程序员(腾讯微云):https://share.weiyun.com/RaCdIwas 1-MySQL基础.pdf.2-MySQL约束与设计.pdf.3-MySQL多表查询与事务 ...

  9. MyBatis:学习笔记(4)——动态SQL

    MyBatis:学习笔记(4)--动态SQL 转载于:https://www.cnblogs.com/MrSaver/p/7453949.html

最新文章

  1. centos 重启网络服务的方法
  2. ext中给文本框赋值的方法_大多数人不知道的Python合并字典的七种方法
  3. MVC模型构建管理系统
  4. ERP与全面预算管理如何结合
  5. linux挂载固硬盘装,linux下安装新硬盘并挂载mount
  6. C++编程笔记:贪心算法实现部分背包问题
  7. NOIP201208同余方程
  8. 懒人建站 前台设计及特效
  9. 趋势安全软件卸载:如何不需要密码或忘记密码卸载Trend Micro OfficeScan Agent?
  10. 基于Pytorch对凸函数采用SGD算法优化实例(附源码)
  11. 曲线运动与万有引力公式_考试中有关曲线运动及万有引力部分ALevel物理考点及公式总结...
  12. SAP中多层扩展有效地bom
  13. HyperLynx(十六)PCI-E的设计与仿真
  14. 使用 bibtex 进行参考文献管理
  15. 使用 libcurl 在windows平台遇到的问题
  16. Day2多种抓包工具介绍以及使用封包监听工具找到挑战数据包实现发送数据包进行挑战
  17. 应用程序无法正常启动(0xc000007b)解决
  18. 全球定位系统GPS简介
  19. python使用ffmpeg去掉视频片头和片尾
  20. 开源中国源码学习(六)——ButterKnife的使用

热门文章

  1. DeepDive自动化信息抽取---全网首发DeepDive偷工减料超速部署方式
  2. caffe安装详细完整过程(Ubuntu16.04、Ubuntu18.04系统)
  3. 【NLP】一文理解Seq2Seq
  4. uniapp 在h5 模式下扫码
  5. 【数据结构】387. 字符串中的第一个唯一字符
  6. Spark~Spark介绍
  7. jQuery(二十二)
  8. ThinkPad E40取消FN功能键设置
  9. redis rua解决库存问题_Redis锁完美解决高并发秒杀问题
  10. 4. 寻找两个正序数组的中位数