NX二次开发-NX连接SqlServer数据库(增删改查)C++版

版本:

客户端NX11+VS2013

服务器windowsServer2012R2+SqlServer2014

使用了ADO方式连接,详细步骤就不写了,可自行百度或参考C#那篇https://www.cnblogs.com/nxopen2018/p/13687882.html

NX11+VS2013

//database

// Mandatory UF Includes
#include <uf.h>
#include <uf_object_types.h>

// Internal Includes
#include <NXOpen/ListingWindow.hxx>
#include <NXOpen/NXMessageBox.hxx>
#include <NXOpen/UI.hxx>

// Internal+External Includes
#include <NXOpen/Annotations.hxx>
#include <NXOpen/Assemblies_Component.hxx>
#include <NXOpen/Assemblies_ComponentAssembly.hxx>
#include <NXOpen/Body.hxx>
#include <NXOpen/BodyCollection.hxx>
#include <NXOpen/Face.hxx>
#include <NXOpen/Line.hxx>
#include <NXOpen/NXException.hxx>
#include <NXOpen/NXObject.hxx>
#include <NXOpen/Part.hxx>
#include <NXOpen/PartCollection.hxx>
#include <NXOpen/Session.hxx>


#include <uf.h>
#include <uf_ui.h>
#import "C:/Program Files/Common Files/System/ado/msado15.dll" no_namespace rename("EOF","adoEOF")


// Std C++ Includes
#include <iostream>
#include <sstream>

using namespace NXOpen;
using std::string;
using std::exception;
using std::stringstream;
using std::endl;
using std::cout;
using std::cerr;


//------------------------------------------------------------------------------
// NXOpen c++ test class 
//------------------------------------------------------------------------------
class MyClass
{
    // class members
public:
    static Session *theSession;
    static UI *theUI;

    MyClass();
    ~MyClass();

    void do_it();
    void print(const NXString &);
    void print(const string &);
    void print(const char*);

private:
    Part *workPart, *displayPart;
    NXMessageBox *mb;
    ListingWindow *lw;
    LogFile *lf;
};

//------------------------------------------------------------------------------
// Initialize static variables
//------------------------------------------------------------------------------
Session *(MyClass::theSession) = NULL;
UI *(MyClass::theUI) = NULL;

//------------------------------------------------------------------------------
// Constructor 
//------------------------------------------------------------------------------
MyClass::MyClass()
{

    // Initialize the NX Open C++ API environment
    MyClass::theSession = NXOpen::Session::GetSession();
    MyClass::theUI = UI::GetUI();
    mb = theUI->NXMessageBox();
    lw = theSession->ListingWindow();
    lf = theSession->LogFile();

    workPart = theSession->Parts()->Work();
    displayPart = theSession->Parts()->Display();
    
}

//------------------------------------------------------------------------------
// Destructor
//------------------------------------------------------------------------------
MyClass::~MyClass()
{
}

//------------------------------------------------------------------------------
// Print string to listing window or stdout
//------------------------------------------------------------------------------
void MyClass::print(const NXString &msg)
{
    if(! lw->IsOpen() ) lw->Open();
    lw->WriteLine(msg);
}
void MyClass::print(const string &msg)
{
    if(! lw->IsOpen() ) lw->Open();
    lw->WriteLine(msg);
}
void MyClass::print(const char * msg)
{
    if(! lw->IsOpen() ) lw->Open();
    lw->WriteLine(msg);
}




//------------------------------------------------------------------------------
// Do something
//------------------------------------------------------------------------------
void MyClass::do_it()
{

    // TODO: add your code here
    
    UF_initialize();
    

    try
    {
        ::CoInitialize(NULL);//初始化OLE/COM库环境,为访问ADO接口做准备

        //实例化
        _ConnectionPtr pConn(__uuidof(Connection));
        _RecordsetPtr pRec(__uuidof(Recordset));
        _CommandPtr pCmd(__uuidof(Command));

        pConn.CreateInstance("ADODB.Connection");//创建连接对象(_Connection)
        pRec.CreateInstance("ADODB.Recordset");//创建记录集对象(_RecordSet)
        pCmd.CreateInstance("ADODB.Command");//创建命令对象(_Command)

        //连接数据库
        string con_str = "Provider=SQLOLEDB;Server=192.168.48.128;Database=MyTest;uid=sa;pwd=Lu123456;";
        _bstr_t strConnect = con_str.c_str();
        pConn->Open(strConnect, "", "", adModeUnknown);
        if (pConn == NULL)
        {
            cerr << "Lind data ERROR!
";
        }

        
        ////insert语句
        //string strSQL11 = "INSERT[dbo].[test1]([学号], [姓名]) VALUES(2,N'李四')";
        //pConn->Execute(_bstr_t(strSQL11.c_str()), NULL, adCmdText);


        ////delete语句
        //string strSQL22 = "delete from[dbo].[test1] where[学号] = 2";
        //pConn->Execute(_bstr_t(strSQL22.c_str()), NULL, adCmdText);

        
        ////update语句
        //string strSQL = "update [dbo].[test1] set [姓名]='李四' where [学号]=1";
        //pConn->Execute(_bstr_t(strSQL.c_str()), NULL, adCmdText);


        //select语句
        //三种方法都可以
        //连接对象
        string strSQL1 = "select * from [dbo].[test1]";     //方法1
        pRec = pConn->Execute(_bstr_t(strSQL1.c_str()), NULL, adCmdText);

        ////记录集对象
        //string strSQL2 = "select * from [dbo].[test1]";           //方法2
        //pRec->Open(_variant_t(strSQL2.c_str()), (_variant_t)((IDispatch*)pConn), adOpenDynamic, adLockOptimistic, adCmdText);

        ////命令对象
        //string strSQL3 = "select * from [dbo].[test1]";         //方法3
        //pCmd->put_ActiveConnection((_variant_t)((IDispatch*)pConn));
        //pCmd->CommandText = _bstr_t(strSQL3.c_str());
        //pRec = pCmd->Execute(NULL, NULL, adCmdText);

        //数据使用
        UF_UI_open_listing_window();
        while (!pRec->adoEOF)
        {
            //_bstr_t类型可以视作COM类型字符串和MFC类型字符串之间的桥梁

            string str = LPSTR(_bstr_t(pRec->GetCollect("姓名")));

            UF_UI_write_listing_window(str.c_str());
            UF_UI_write_listing_window("
");

            pRec->MoveNext();
        }


        //关闭与释放
        pRec->Close();
        pConn->Close();
        pRec.Release();
        pCmd.Release();
        pConn.Release();

    }
    catch (_com_error& e)
    {
        uc1601(e.ErrorMessage(), 1);

        uc1601(e.Description(), 1);
    }

    uc1601("完成", 1);

    UF_terminate();

}

//------------------------------------------------------------------------------
// Entry point(s) for unmanaged internal NXOpen C/C++ programs
//------------------------------------------------------------------------------
//  Explicit Execution
extern "C" DllExport void ufusr( char *parm, int *returnCode, int rlen )
{
    try
    {
        // Create NXOpen C++ class instance
        MyClass *theMyClass;
        theMyClass = new MyClass();
        theMyClass->do_it();
        delete theMyClass;
    }
    catch (const NXException& e1)
    {
        UI::GetUI()->NXMessageBox()->Show("NXException", NXOpen::NXMessageBox::DialogTypeError, e1.Message());
    }
    catch (const exception& e2)
    {
        UI::GetUI()->NXMessageBox()->Show("Exception", NXOpen::NXMessageBox::DialogTypeError, e2.what());
    }
    catch (...)
    {
        UI::GetUI()->NXMessageBox()->Show("Exception", NXOpen::NXMessageBox::DialogTypeError, "Unknown Exception.");
    }
}


//------------------------------------------------------------------------------
// Unload Handler
//------------------------------------------------------------------------------
extern "C" DllExport int ufusr_ask_unload()
{
    return (int)NXOpen::Session::LibraryUnloadOptionImmediately;
}


Caesar卢尚宇
2020年10月22日

Caesar卢尚宇

2020年10月22日

原文地址:https://www.cnblogs.com/nxopen2018/p/13861194.html