简体   繁体   English

如何在Linux上从C ++连接并执行对SQL Server的简单查询

[英]How to connect and execute a simple query to SQL Server from C++ on Linux

I guess, I have all prerequisites for setting connection and querying SQL Server database, since I can do that from my Python code. 我想,我具有设置连接和查询SQL Server数据库的所有先决条件,因为我可以从我的Python代码中做到这一点。 And I do this like so: 我这样做是这样的:

#1. Set connection using pyodbc library

db = pyodbc('DRIVER=FreeTDS;SERVER='+host+';PORT='+port+';DATABASE='+ \
            db_name+ ';UID='+ user+ ';PWD='+ pwd+ ';TDS_Version=7.0;ClientCharset=UTF8;') 

#2. List all table names in a particular database

cursor = db.cursor()
cursor.execute('SELECT TABLE_NAME FROM ' + db_name + '.INFORMATION_SCHEMA.Tables WHERE ' + \
'TABLE_TYPE=\'BASE TABLE\'')
res = cursor.fetchall()

And I'm done. 我完成了。 Now I want to implement the same thing, using C++ . 现在,我想使用C++实现同一件事。 I've seen some sample codes like this , but they look awfully terrible with five if s nested one into another. 我已经看到了一些像这样的示例代码,但是if将五个嵌套在一起,它们看起来非常糟糕。 But I need something really simple, taking into consideration that probably all prerequisites are met (if may be not, please, instruct what else should be installed). 但是我需要一个非常简单的方法,考虑到可能满足了所有先决条件(如果可能不满足,请指示还应该安装什么)。

The last thing I want to know is indeed how to compile this program (I normally do this using g++ ). 我想知道的最后一件事确实是如何编译该程序(我通常使用g++进行此操作)。 And, please, do not post sole references to FreeTDS and ODBC - I've already seen them. 而且,请不要发布对FreeTDSODBC唯一引用-我已经看过它们。 What I want at this stage is a tiny minimized example of executing the simplest in the world query (like I did it above, using Python ). 在这个阶段,我想要的是一个最小的最小化示例,它执行世界上最简单的查询(就像我上面使用Python所做的那样)。

This is not tested with freetds driver of unixodbc. 尚未使用unixodbc的freetds驱动程序进行测试。 This is how i setup unixodbc with postgres or mysql. 这就是我用postgres或mysql设置unixodbc的方式。 https://k3ut0i.github.io/work/2015/08/09/odbc-setup-linux.html https://k3ut0i.github.io/work/2015/08/09/odbc-setup-linux.html

The global setup of drivers and data sources for ODBC are in /etc/odbc.ini and /etc/odbcinst.ini . ODBC的驱动程序和数据源的全局设置位于/etc/odbc.ini/etc/odbcinst.ini some operating systems may have these files empty or differenet names. 某些操作系统可能使这些文件为空或不同的名称。 Here are my config files. 这是我的配置文件。

Drivers, libraries in /etc/odbcinst.ini file. 驱动程序,/ etc / odbcinst.ini文件中的库。

    [MySQL]
    Description     = ODBC driver for mariaDB
    Driver          = /usr/lib/libmyodbc.so
    Setup           = /usr/lib/libmyodbc5S.so
    FileUsage       = 1

the pyodbc function in the python file is equivalent a data source in /etc/odbc.ini file. python文件中的pyodbc函数等效于/etc/odbc.ini文件中的数据源。

    [mariadb-connector]
    Description     = connection to test database for mariadb
    Driver          = MySQL
    Database        = test
    Server          = 127.0.0.1
    UserName        = keutoi
    Trace           = No
    Port            = 3306

Part of the code that connects and query. 连接和查询的部分代码。 I just started from your link and cleaned it up. 我只是从您的链接开始,然后进行了清理。

        /**
         * Connect to data source named in /etc/odbc.ini file
         */
        retcode = SQLDriverConnect(hdbc, NULL, (SQLCHAR*)"DSN=mariadb-connector;", SQL_NTS, outstr, sizeof(outstr), &outstrlen, SQL_DRIVER_COMPLETE);
        check_error(retcode, "connect to the data source");

        //Allocate statement handle
        retcode = SQLAllocHandle(SQL_HANDLE_STMT, hdbc, &hstmt);
        check_error(retcode, "allocate a statement handle");

        /**
         * statement to be executed.
         */
        retcode = SQLExecDirect (hstmt, (SQLCHAR *) "select * from mytable", SQL_NTS);
        check_error(retcode, "execute the statement");

        /**
         * Bind a column to a variable
         */
        retcode = SQLBindCol(hstmt, 1, SQL_C_CHAR, szName, NAME_LEN, &cbName);
        check_error(retcode, "bind 1 column to the statement");
        retcode = SQLBindCol(hstmt, 2, SQL_C_CHAR, szID, ID_LEN, &cbID);
        check_error(retcode, "bind 2 column to the statement");

        /**
         * fetch sql hstmt untill there is no data and print
         */
        for (int i=0 ; ; i++)
        {
            retcode = SQLFetch(hstmt);
            if(retcode == SQL_NO_DATA)break;
            else printf( "%d: %s %s %s\n", i + 1, szID, szName);
        }

Complete example is here . 完整的例子在这里 Compile with g++ file.cc -lodbc g++ file.cc -lodbc编译

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM