zoukankan      html  css  js  c++  java
  • NX二次开发-NX访问MySQL数据库(增删改查)

    版本:NX11+VS2013+MySQL5.6(x64)+SQLyog

    1.新建一个NX项目(多字节)

    2.设置VC++目录(调用MySQL的头文件,dll和lib库文件)

    3.设置番茄助手

     

     然后重启VS

    3.源代码(发布:程序运行时需要libmysql.dll,此DLL要随程序一同发布)

      1 //DataBaseTest
      2 
      3 // Mandatory UF Includes
      4 #include <uf.h>
      5 #include <uf_object_types.h>
      6 
      7 // Internal Includes
      8 #include <NXOpen/ListingWindow.hxx>
      9 #include <NXOpen/NXMessageBox.hxx>
     10 #include <NXOpen/UI.hxx>
     11 
     12 // Internal+External Includes
     13 #include <NXOpen/Annotations.hxx>
     14 #include <NXOpen/Assemblies_Component.hxx>
     15 #include <NXOpen/Assemblies_ComponentAssembly.hxx>
     16 #include <NXOpen/Body.hxx>
     17 #include <NXOpen/BodyCollection.hxx>
     18 #include <NXOpen/Face.hxx>
     19 #include <NXOpen/Line.hxx>
     20 #include <NXOpen/NXException.hxx>
     21 #include <NXOpen/NXObject.hxx>
     22 #include <NXOpen/Part.hxx>
     23 #include <NXOpen/PartCollection.hxx>
     24 #include <NXOpen/Session.hxx>
     25 
     26 #include <uf.h>
     27 #include <uf_ui.h>
     28 
     29 //头文件
     30 #include <stdio.h>
     31 #include <stdlib.h>
     32 //MySQL support on Windows
     33 #include <WinSock2.h>
     34 #include <mysql.h>
     35 #pragma comment(lib,"libmysql")
     36 
     37 
     38 
     39 // Std C++ Includes
     40 #include <iostream>
     41 #include <sstream>
     42 
     43 using namespace NXOpen;
     44 using std::string;
     45 using std::exception;
     46 using std::stringstream;
     47 using std::endl;
     48 using std::cout;
     49 using std::cerr;
     50 
     51 
     52 //------------------------------------------------------------------------------
     53 // NXOpen c++ test class 
     54 //------------------------------------------------------------------------------
     55 class MyClass
     56 {
     57     // class members
     58 public:
     59     static Session *theSession;
     60     static UI *theUI;
     61 
     62     MyClass();
     63     ~MyClass();
     64 
     65     void do_it();
     66     void print(const NXString &);
     67     void print(const string &);
     68     void print(const char*);
     69 
     70 private:
     71     Part *workPart, *displayPart;
     72     NXMessageBox *mb;
     73     ListingWindow *lw;
     74     LogFile *lf;
     75 };
     76 
     77 //------------------------------------------------------------------------------
     78 // Initialize static variables
     79 //------------------------------------------------------------------------------
     80 Session *(MyClass::theSession) = NULL;
     81 UI *(MyClass::theUI) = NULL;
     82 
     83 //------------------------------------------------------------------------------
     84 // Constructor 
     85 //------------------------------------------------------------------------------
     86 MyClass::MyClass()
     87 {
     88 
     89     // Initialize the NX Open C++ API environment
     90     MyClass::theSession = NXOpen::Session::GetSession();
     91     MyClass::theUI = UI::GetUI();
     92     mb = theUI->NXMessageBox();
     93     lw = theSession->ListingWindow();
     94     lf = theSession->LogFile();
     95 
     96     workPart = theSession->Parts()->Work();
     97     displayPart = theSession->Parts()->Display();
     98     
     99 }
    100 
    101 //------------------------------------------------------------------------------
    102 // Destructor
    103 //------------------------------------------------------------------------------
    104 MyClass::~MyClass()
    105 {
    106 }
    107 
    108 //------------------------------------------------------------------------------
    109 // Print string to listing window or stdout
    110 //------------------------------------------------------------------------------
    111 void MyClass::print(const NXString &msg)
    112 {
    113     if(! lw->IsOpen() ) lw->Open();
    114     lw->WriteLine(msg);
    115 }
    116 void MyClass::print(const string &msg)
    117 {
    118     if(! lw->IsOpen() ) lw->Open();
    119     lw->WriteLine(msg);
    120 }
    121 void MyClass::print(const char * msg)
    122 {
    123     if(! lw->IsOpen() ) lw->Open();
    124     lw->WriteLine(msg);
    125 }
    126 
    127 
    128 //------------------------------------------------------------------------------
    129 // 定义结构体
    130 //------------------------------------------------------------------------------
    131 struct Student
    132 {
    133     int id;
    134     char name[32];
    135     char birthday[16];
    136     char cellphone[12];
    137 };
    138 
    139 
    140 //------------------------------------------------------------------------------
    141 // 接收界面输入参数,增加一条数据
    142 //------------------------------------------------------------------------------
    143 int do_insert(Student* stu)
    144 {
    145     MYSQL conn;
    146     mysql_init(&conn);
    147 
    148     // 连接服务器
    149     if (NULL == mysql_real_connect(&conn,
    150         "127.0.0.1", "root", "123456", "example"
    151         , 0, NULL, 0))
    152     {
    153         printf("Failed to connect to database:  %s
    ",
    154             mysql_error(&conn));
    155         return -1;
    156     }
    157 
    158     // 构造SQL语句
    159     char sql[256];
    160     sprintf(sql,
    161         "   INSERT INTO `student` "
    162         "       (`id`, `name`, `birthday`, `cellphone`)    "
    163         "        VALUES   "
    164         "('%d', '%s', '%s', '%s')"
    165         , stu->id
    166         , stu->name
    167         , stu->birthday
    168         , stu->cellphone
    169         );
    170 
    171     // 执行SQL语句
    172     int ret = mysql_query(&conn, sql);
    173     if (ret != 0)
    174     {
    175         printf("error: %s 
    ", mysql_error(&conn));
    176     }
    177     else
    178     {
    179         my_ulonglong affected_rows = mysql_affected_rows(&conn); // a 64-bit large number
    180         printf("%d rows affected. 
    ", (int)affected_rows); // cast to int
    181     }
    182 
    183     // 关闭连接
    184     mysql_close(&conn);
    185 
    186     return 0;
    187 }
    188 
    189 
    190 //------------------------------------------------------------------------------
    191 // 增加一条数据
    192 //------------------------------------------------------------------------------
    193 int my_insert(MYSQL* conn)
    194 {
    195     //SQL语句的末尾不要加分号
    196     const char* sql =
    197         "   INSERT INTO `student` "
    198         "       (`id`, `name`, `birthday`, `cellphone`)    "
    199         "        VALUES   "
    200         "('17', 'qian22', '1992-12-2', '18601088987')"
    201         ;
    202 
    203     int ret = mysql_query(conn, sql);//执行SQL语句
    204     char msg[256];
    205     if (ret != 0)
    206     {    
    207         sprintf_s(msg, "error: %s
    ", conn, sql);
    208         uc1601(msg, 1);
    209         return -1;
    210     }
    211     my_ulonglong affected_rows = mysql_affected_rows(conn);//获得受影响的行数
    212     sprintf_s(msg, "%d rows affected
    ", (int)affected_rows);
    213     uc1601(msg, 1);
    214 
    215     return 0;
    216 }
    217 
    218 
    219 //------------------------------------------------------------------------------
    220 // 查找数据
    221 //------------------------------------------------------------------------------
    222 int my_select(MYSQL* conn)
    223 {
    224     // SQL语句,末尾不加分号。每次只执行一条SQL语句。
    225     const char* sql = "SELECT * FROM student";
    226     int ret = mysql_query(conn, sql);
    227     char msg[256];
    228     UF_UI_open_listing_window();
    229     if (ret != 0)
    230     {
    231         sprintf_s(msg,"error: %s 
    ", mysql_error(conn));
    232         uc1601(msg, 1);
    233         return -1;
    234     }
    235 
    236     MYSQL_RES * result = mysql_store_result(conn);
    237     if (result == NULL)
    238     {
    239         //printf("error(%d): %s 
    ", mysql_errno(conn), mysql_error(conn));
    240     }
    241     else
    242     {
    243         // how many rows
    244         my_ulonglong num_rows = mysql_num_rows(result);
    245         sprintf_s(msg,"got %d rows: 
    ", (int)num_rows);
    246         UF_UI_write_listing_window(msg);
    247 
    248         // number of fields for each row
    249         unsigned int num_fields = mysql_num_fields(result);
    250         sprintf_s(msg,"number of fields: %d 
    ", (int)num_fields);
    251         UF_UI_write_listing_window(msg);
    252 
    253         // fetch the rows
    254         MYSQL_ROW row;
    255         while ((row = mysql_fetch_row(result)))
    256         {
    257             unsigned long *lengths = mysql_fetch_lengths(result);
    258             for (int i = 0; i < num_fields; i++)
    259             {
    260                 char* field = row[i]; // can be a NULL value
    261                 unsigned int field_length = lengths[i]; // the data length
    262 
    263                 sprintf_s(msg,"     column[%d], length[%d] , data[%s] 
    ",
    264                     i, field_length, field ? field : "null");
    265                 UF_UI_write_listing_window(msg);
    266             }
    267             UF_UI_write_listing_window("
    ");
    268         }
    269 
    270         // release the memory
    271         mysql_free_result(result);
    272     }
    273 
    274     return 0;
    275 }
    276 
    277 //------------------------------------------------------------------------------
    278 // Do something
    279 //------------------------------------------------------------------------------
    280 void MyClass::do_it()
    281 {
    282 
    283     // TODO: add your code here
    284 
    285 /*
    286     //获取用户输入
    287     Student stu;
    288     printf("ID:");
    289     char buf[128];
    290     gets(buf);
    291     stu.id = atoi(buf);
    292     printf("Name:");
    293     gets(stu.name);
    294     printf("Birthday:");
    295     gets(stu.birthday);
    296     printf("CellPhone:");
    297     gets(stu.cellphone);
    298 */
    299 
    300     if (mysql_library_init(0, NULL, NULL))//初始化
    301     {
    302         uc1601("could not initialize MySQL library
    ", 1);
    303         return;
    304     }
    305     //连接服务器
    306     MYSQL conn;
    307     mysql_init(&conn);
    308 
    309     MYSQL* ret = mysql_real_connect(&conn, "127.0.0.1", "root", "123456", "example", 0, NULL, 0);
    310     if (!ret)
    311     {
    312         char msg[256];
    313         sprintf_s(msg, "Failed to connect to database: %s
    ", mysql_error(&conn));
    314         uc1601(msg, 1);
    315     }
    316 
    317     //增加一条数据
    318     my_insert(&conn);
    319 
    320     //查找数据
    321     my_select(&conn);
    322 
    323     //关闭连接
    324     mysql_close(&conn);
    325 
    326     mysql_library_end();//结束
    327 }
    328 
    329 //------------------------------------------------------------------------------
    330 // Entry point(s) for unmanaged internal NXOpen C/C++ programs
    331 //------------------------------------------------------------------------------
    332 //  Explicit Execution
    333 extern "C" DllExport void ufusr( char *parm, int *returnCode, int rlen )
    334 {
    335     try
    336     {
    337         // Create NXOpen C++ class instance
    338         MyClass *theMyClass;
    339         theMyClass = new MyClass();
    340         theMyClass->do_it();
    341         delete theMyClass;
    342     }
    343     catch (const NXException& e1)
    344     {
    345         UI::GetUI()->NXMessageBox()->Show("NXException", NXOpen::NXMessageBox::DialogTypeError, e1.Message());
    346     }
    347     catch (const exception& e2)
    348     {
    349         UI::GetUI()->NXMessageBox()->Show("Exception", NXOpen::NXMessageBox::DialogTypeError, e2.what());
    350     }
    351     catch (...)
    352     {
    353         UI::GetUI()->NXMessageBox()->Show("Exception", NXOpen::NXMessageBox::DialogTypeError, "Unknown Exception.");
    354     }
    355 }
    356 
    357 
    358 //------------------------------------------------------------------------------
    359 // Unload Handler
    360 //------------------------------------------------------------------------------
    361 extern "C" DllExport int ufusr_ask_unload()
    362 {
    363     return (int)NXOpen::Session::LibraryUnloadOptionImmediately;
    364 }
    365 
    366 
    367 Caesar卢尚宇
    368 2020年2月12日

    4.补充(出自https://chuanke.baidu.com/v4509752-209102-1284621.html C语言C++学习指南(数据库篇)MySQL与SQLite)

     

    学习资料 https://chuanke.baidu.com/v4509752-209102-1284621.html C语言C++学习指南(数据库篇)MySQL与SQLite

     MySQL https://www.mysql.com/

    MySQL :: MySQL 5.6 Reference Manual :: 23.7.5 C API Function Overview https://dev.mysql.com/doc/refman/5.6/en/c-api-function-overview.html

    补充

    数据库不能写入中文,设置数据库字符集,// "gbk" or "utf8"

    位置加到mysql_init之后,mysql_real_connect之前。

            // "gbk" or "utf8"
            if (!mysql_set_character_set(&conn, "gbk"))
            {
                char msg[256];
                sprintf_s(msg, "Charset for the connection : %s
    ", mysql_character_set_name(&conn));
                //uc1601(msg, 1);
            }

    2020年4月27日

    Caesar卢尚宇

  • 相关阅读:
    Qt CheckBox选中与未选中的使用
    Qt Excel表格宽高的设置
    VTK三维重建 使用VTK读取DICOM,并动态输出
    VC++ VTK 读取序列CT图片三维重建
    VTK 读取序列图像
    Qt QWidget提升QVTKWidget
    ITK 介绍
    Qt QMainWindow中利用多个QDockWidget构成标签页tab || tabifyDockWidget
    Qt QDockWidget属性 setFeatures、setAllowedAreas
    Qt Designer中toolBar的allowedAreas属性
  • 原文地址:https://www.cnblogs.com/nxopen2018/p/12297590.html
Copyright © 2011-2022 走看看