Qt remote connection SQL Server 2008 r2

  Company leaders said the hospital to keep a database butt, I'll get to know the SQL Server 2008 r2, in fact, when the school learned, but learning some basic operations. The Qt try connecting remote.

He turned over two days, finally able to connect to the database in another computer in the same local area network using qt PC. The process to be a blog about it.

Certainly the first step is to install SQL Server 2008 r2. This online tutorial lot, but I do not recommend, recommend the direct use of the official website of the installation package, the Internet is too big.

Official website connection: https: //www.microsoft.com/zh-cn/download/confirmation.aspx id = 23650 I use this installation package and what did not use the activation code, or good?.

After the download is complete run, a good idea to organize a computer disk for storing SQL Server 2008 r2.

 

 Select the installation, enter the installation program page.

 

 Click Install,

 

 Accept the license terms, the next step.

 

Click Select, change the directory, simply change the disc which can be placed in the back of the folder do not change. Click Next.

 

 Examples of the root directory is also changed, the next step.

 

 Both services startup type set to automatic. The next step

 

 Select Mixed Mode, set a password, add the current user, I've had the computer login user added to the list, the next step, then the next step, enter the installation page

 

 Wait for the installation to complete. Click to close

 

 Just run the installation of SQL Server Management Studio

Enter the connection page:

 

 Select the local server name is the machine, select the authentication SQL Server authentication, login name sa, password is the password set when just installed. Click the connection.

Now create a database

 

Click New Query, and enter the following code:

CREATE DATABASE Bank;

Click execute, then delete the above, and then enter the following code

use Bank;
CREATE TABLE Card
( Account INT PRIMARY KEY,
  Pwd VARCHAR(12) NOT NULL,
  Balance INT CHECK(Balance>=0)
 )

 CREATE TABLE Record
 ( Account INT FOREIGN KEY(Account) REFERENCES Card(Account),
   Rmoney INT,
   Rtime DATETIME NOT NULL DEFAULT GETDATE()
  )

  INSERT INTO Card VALUES(123456,123456,100000);
  INSERT INTO Record (Account,Rmoney) VALUES (123456,-100);

点击执行,执行成功后点击刷新,即可看到刚刚创建的数据库Bank。

 

 

 接下来就可以开始远程连接了,开始之前先确保两个:

一:服务器允许远程连接,右键点击已连接的服务器,选择'属性',点击左侧‘连接’

 

 二:打开SQL Server配置管理器,选择SQL Server 网络配置 - MSSQLSERVER的协议,右键TCP/IP,选择启用

 

 然后重启服务即可

下一步是关闭电脑防火墙,当然了,最优做法是在防火墙上为SQL Server创建规则,我这里,懒人做法啦。

把这台电脑当做服务器。

然后找另一台和这台服务器在同一局域网下的电脑开始连接测试。

使用ODBC建立数据源,直接在电脑上搜索ODBC即可。打开之后,点击 添加 

 

 

 选择 SQLServer  点击确定

 

 

 

 

 

 填写名称和描述,名称等下程序里要用,描述随便写。服务器选择刚刚安装SQL Server 2008并创建数据库的电脑的IP地址或者电脑名,点击下一步

 

 

 选择 使用用户输入登陆ID和密码的SQL Server验证,然后输入登陆ID和密码,也就是服务器电脑数据库的ID和密码(安装时设置的)。点击下一步。

 

 

 勾选 更改默认的数据库为   ,然后在下拉列表中选择刚刚在服务器中创建的数据库,我这里是Bank。点击下一步

再直接点击完成,再点击 测试数据库连接  直到出现

 

 

 说明ODBC数据源创建成功。可以开始下一步了。

然后写代码进行测试,新建Qt Widgets应用程序,然后修改main.cpp为

#include "mainwindow.h"
#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("tianSQLServer");      //数据源名称   刚刚创建的数据源的名称
    db.setHostName("Yct201909041134");                        //选择IP地址,也就是服务器的IP地址或者电脑名
    db.setDatabaseName(dsn);                            //设置数据源名称
    db.setUserName("sa");                               //登录用户  创建数据源时输入大的用户名和密码
    db.setPassword("tian");                              //密码  
    if(!db.open())                                      //打开数据库
    {
        qDebug()<<db.lastError().text();
        QMessageBox::critical(0, QObject::tr("Database error"), db.lastError().text());
        return false;                                   //打开失败
    }
    else
    {
        qDebug()<<"database open success!";
        QSqlQuery query(db); //查询Card表并输出,测试能否正常操作数据库
        query.exec("SELECT * FROM Card");
        while(query.next())
        {
            qDebug()<<query.value(0).toInt() <<query.value(1).toString() <<query.value(2).toInt();
        }

    }return true;
}

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;

    if(!OpenDatabase())
        return 1;

    w.show();
    return a.exec();
}

运行程序可以在控制台看到输出

 

 

下面还有一个不需要创建ODBC数据源即可远程连接SQL Server数据库的方法。

//网络数据库SQL访问
/***************************************************************************
 * 函数名:openSQLServer
 * 参数1:ip 数据库服务器IP
 * 参数2:dbName 数据库名称
 * 参数3:userName 用户名
 * 参数4:passwd   密码
 * 返回 true 打开数据库成功
 * ************************************************************************/
bool MainWindow::openSQLServer(const QString ip,const QString dbName,const QString userName,const QString passwd)
{
       db = QSqlDatabase::addDatabase("QODBC");  //数据库驱动类型为SQL Server
       qDebug()<<"ODBC driver?"<<db.isValid();
       QString dsn = QString("DRIVER={SQL SERVER};SERVER=%1;DATABASE=%2").arg(ip).arg(dbName);
       db.setDatabaseName(dsn);
       db.setUserName(userName);                        //登录用户
       db.setPassword(passwd);                          //密码
       if(!db.open())                                   //打开数据库
       {
           qDebug()<<db.lastError().text();
           QMessageBox::critical(0, QObject::tr("Database error"), db.lastError().text());
           return false;                                   //打开失败
       }
       else
       {
           qDebug()<<"database open success!";
           QMessageBox::critical(0, QObject::tr("Database ok"),"数据库打开成功");
           QSqlQuery query(db); //查询Card表并输出,测试能否正常操作数据库
           query.exec("select * from [Bank].[dbo].[Card]");
           while(query.next())
           {
               qDebug()<<query.value(0).toString()  <<query.value(1).toString() <<query.value(2).toString();
           }

       }
       return true;
}

说明:此代码里的参数dbName是数据库名,也就是服务器中创建的数据库的名字,像我这里就是Bank,可以做一下修改,移植到刚刚的代码里看效果。

 

Guess you like

Origin www.cnblogs.com/tianxxl/p/11851495.html