• Lunes 29 de Abril de 2024, 07:05

Autor Tema:  Visual C++ MySQL Server Embebido  (Leído 1869 veces)

Señor X²

  • Nuevo Miembro
  • *
  • Mensajes: 16
    • Ver Perfil
Visual C++ MySQL Server Embebido
« en: Martes 31 de Marzo de 2009, 23:45 »
0
Hola, hace un tiempo programo en Visual C++ 2008 usando las API y accediendo a MySQL también por medio de las API, hasta ahí todo bien, el tema es que ahora quiero usar la opción de servidor embebido haciando uso de la librería libmysqld.dll, para no tener que instalar MySQL en cada máquina donde voy a ejecutar mis programas. Pero no he podido hacerlo andar, hace un par de semanas ya que vengo renegando con esto y no he podido hacerlo andar.

Encontré mucha información, pero toda para Linux y lo que me interesa es sobre windows.

En esta página hay un tutorial que lo explica en windows y el linux, pero no he podido hacerlo andar, se produce un error en tiempo de ejecución y se cierra todo

hxxp://shivasdairy.blogspot.com/2007/01 ... erver.html
(puse hXXp porque no tengo privilegios para publicar enlaces) perdón si no se puede

Muchas Gracias

Señor X²

  • Nuevo Miembro
  • *
  • Mensajes: 16
    • Ver Perfil
Re: Visual C++ MySQL Server Embebido
« Respuesta #1 en: Martes 5 de Mayo de 2009, 15:41 »
0
bueno, después de un tiempo pude hacerlo andar, si a alguien le interesa, avisen

jhonpoiron

  • Nuevo Miembro
  • *
  • Mensajes: 1
    • Ver Perfil
Re: Visual C++ MySQL Server Embebido
« Respuesta #2 en: Miércoles 20 de Mayo de 2009, 20:31 »
0
Hola. creo que soy un novato en aplicaciones que incrusten mysql. por lo tanto me interisaria los pasos necesarios para embeber mysql desde visual. DE antemano gracias por la atencion prestada.
POIRON

Señor X²

  • Nuevo Miembro
  • *
  • Mensajes: 16
    • Ver Perfil
Re: Visual C++ MySQL Server Embebido
« Respuesta #3 en: Jueves 21 de Mayo de 2009, 16:13 »
0
·         Incluimos
Código: C++
  1. #include "winsock.h"
  2. #include "mysql.h"
  3.  

·         Asignamos la dependencia a la librería libmysqld

Project -> Properties (ALT+F7)

Configuration Properties -> Linker -> Input

Additional Dependencies libmysqld.lib

El archivo se encuentra ubicado en: C:Archivos de programaMySQLMySQL Server 5.1EmbeddedDLLrelease o debug, respectivamente.
Si no se encuentra el archivo, ver la instalación de MySQL, ya que nos ofrece instalar o no los archivos del servidor embebido.
Entonces programa necesita el archivo libmysqld.dll para correr, de unos 6 MB.

·         Creamos en archivo de configuracion del servidor

Creamos el archivo my.ini con el siguiente contenido

 
Citar
[libmysqld_server]
datadir = C:/datadir
language = C:/windows/

[libmysqld_client]
language = C:/windows/

·         Conectamos al servidor

Código: C++
  1. static char *server_options[] = { "mysql_test", "--defaults-file=C:/Windows/my.ini", NULL };
  2. int num_elements = (sizeof(server_options) / sizeof(char *)) - 1;
  3.  
  4. static char *server_groups[] = { "libmysqld_server", "libmysqld_client", NULL };
  5.  
  6. mysql_library_init(num_elements, server_options, server_groups);
  7.  
  8. myData = mysql_init(NULL);
  9.  
  10. mysql_options(myData, MYSQL_READ_DEFAULT_GROUP, "libmysqld_client");
  11.  
  12. mysql_options(myData, MYSQL_OPT_USE_EMBEDDED_CONNECTION, NULL);
  13.  
  14. mysql_real_connect(myData, NULL,NULL,NULL, NULL, 0,NULL,0);
  15.  

Si el archivo my.ini no se encuentra en la ruta especificada ahí, la función mysql_library_init falla.

En el archivo my.ini, le especificamos 2 carpetas, datadir y language, datadir, es el directorio donde van los datos de las tablas, etc, y language, es el directorio donde se encuentra el archivo con los mensajes de errores (creo que es para eso :P), llamado errmsg.sys el mismo lo encontramos en C:Archivos de programaMySQLMySQL Server 5.1share y el idioma que querramos, yo usé el inglés, pero no creo que haya problemas para usar el español.

MUY IMPORTANTE:

La carpeta datadir, tiene que existir, mysql no la va a crear.

·         Cerramos la conexión

Código: C++
  1. mysql_close(myData);
  2. mysql_library_end();
  3.  

Por último, para realizar las consultas, basta con usar la función mysql_query en cualquier mensaje, ya sea un botón, o cuando se desee. Por supuesto, para hacer las consultas hay que seleccionar la base de datos, eso lo hacemos usando la consulta “USE prueba” o al usar mysql_real_connect en el parametro numero 5.

Acá te dejo el .cpp completo

Código: C++
  1. // mysql_embedded_visual.cpp : Defines the entry point for the application.
  2. //
  3.  
  4. #include "stdafx.h"
  5. #include "mysql_embedded_visual.h"
  6.  
  7. #include "winsock.h"
  8. #include "mysql.h"
  9.  
  10. #define MAX_LOADSTRING 100
  11.  
  12. // Global Variables:
  13. HINSTANCE hInst;                                // current instance
  14. TCHAR szTitle[MAX_LOADSTRING];                  // The title bar text
  15. TCHAR szWindowClass[MAX_LOADSTRING];            // the main window class name
  16.  
  17. /* Declaramos la variable myData */
  18. MYSQL *myData;
  19.  
  20. // Forward declarations of functions included in this code module:
  21. ATOM                MyRegisterClass(HINSTANCE hInstance);
  22. BOOL                InitInstance(HINSTANCE, int);
  23. LRESULT CALLBACK    WndProc(HWND, UINT, WPARAM, LPARAM);
  24. INT_PTR CALLBACK    About(HWND, UINT, WPARAM, LPARAM);
  25.  
  26.  
  27.  
  28. int APIENTRY _tWinMain(HINSTANCE hInstance,
  29.                      HINSTANCE hPrevInstance,
  30.                      LPTSTR    lpCmdLine,
  31.                      int       nCmdShow)
  32. {
  33.     UNREFERENCED_PARAMETER(hPrevInstance);
  34.     UNREFERENCED_PARAMETER(lpCmdLine);
  35.  
  36.     // TODO: Place code here.
  37.     MSG msg;
  38.     HACCEL hAccelTable;
  39.  
  40.     // Initialize global strings
  41.     LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
  42.     LoadString(hInstance, IDC_MYSQL_EMBEDDED_VISUAL, szWindowClass, MAX_LOADSTRING);
  43.     MyRegisterClass(hInstance);
  44.  
  45.     // Perform application initialization:
  46.     if (!InitInstance (hInstance, nCmdShow))
  47.     {
  48.         return FALSE;
  49.     }
  50.  
  51.     hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_MYSQL_EMBEDDED_VISUAL));
  52.  
  53.     // Main message loop:
  54.     while (GetMessage(&msg, NULL, 0, 0))
  55.     {
  56.         if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
  57.         {
  58.             TranslateMessage(&msg);
  59.             DispatchMessage(&msg);
  60.         }
  61.     }
  62.  
  63.     return (int) msg.wParam;
  64. }
  65.  
  66.  
  67.  
  68. //
  69. //  FUNCTION: MyRegisterClass()
  70. //
  71. //  PURPOSE: Registers the window class.
  72. //
  73. //  COMMENTS:
  74. //
  75. //    This function and its usage are only necessary if you want this code
  76. //    to be compatible with Win32 systems prior to the 'RegisterClassEx'
  77. //    function that was added to Windows 95. It is important to call this function
  78. //    so that the application will get 'well formed' small icons associated
  79. //    with it.
  80. //
  81. ATOM MyRegisterClass(HINSTANCE hInstance)
  82. {
  83.     WNDCLASSEX wcex;
  84.  
  85.     wcex.cbSize = sizeof(WNDCLASSEX);
  86.  
  87.     wcex.style          = CS_HREDRAW | CS_VREDRAW;
  88.     wcex.lpfnWndProc    = WndProc;
  89.     wcex.cbClsExtra     = 0;
  90.     wcex.cbWndExtra     = 0;
  91.     wcex.hInstance      = hInstance;
  92.     wcex.hIcon          = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_MYSQL_EMBEDDED_VISUAL));
  93.     wcex.hCursor        = LoadCursor(NULL, IDC_ARROW);
  94.     wcex.hbrBackground  = (HBRUSH)(COLOR_BTNFACE+1);
  95.     wcex.lpszMenuName   = MAKEINTRESOURCE(IDC_MYSQL_EMBEDDED_VISUAL);
  96.     wcex.lpszClassName  = szWindowClass;
  97.     wcex.hIconSm        = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL));
  98.  
  99.     return RegisterClassEx(&wcex);
  100. }
  101.  
  102. //
  103. //   FUNCTION: InitInstance(HINSTANCE, int)
  104. //
  105. //   PURPOSE: Saves instance handle and creates main window
  106. //
  107. //   COMMENTS:
  108. //
  109. //        In this function, we save the instance handle in a global variable and
  110. //        create and display the main program window.
  111. //
  112. BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
  113. {
  114.    HWND hWnd;
  115.  
  116.    hInst = hInstance; // Store instance handle in our global variable
  117.  
  118.    hWnd = CreateWindow(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW,
  119.       CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL);
  120.  
  121.    if (!hWnd)
  122.    {
  123.       return FALSE;
  124.    }
  125.  
  126.    ShowWindow(hWnd, nCmdShow);
  127.    UpdateWindow(hWnd);
  128.  
  129.    return TRUE;
  130. }
  131.  
  132. //
  133. //  FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM)
  134. //
  135. //  PURPOSE:  Processes messages for the main window.
  136. //
  137. //  WM_COMMAND  - process the application menu
  138. //  WM_PAINT    - Paint the main window
  139. //  WM_DESTROY  - post a quit message and return
  140. //
  141. //
  142. LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
  143. {
  144.     int wmId, wmEvent;
  145.     PAINTSTRUCT ps;
  146.     HDC hdc;
  147.  
  148.     switch (message)
  149.     {
  150.     case WM_CREATE:
  151.         {
  152.  
  153.             static char *server_options[] = { "mysql_test", "--defaults-file=C:/Windows/my.ini", NULL };
  154.             int num_elements = (sizeof(server_options) / sizeof(char *)) - 1;
  155.  
  156.             static char *server_groups[] = { "libmysqld_server",
  157.                                              "libmysqld_client",
  158.                                              NULL };
  159.  
  160.             mysql_library_init(num_elements, server_options, server_groups);
  161.  
  162.             myData = mysql_init(NULL);
  163.  
  164.             mysql_options(myData, MYSQL_READ_DEFAULT_GROUP, "libmysqld_client");
  165.             mysql_options(myData, MYSQL_OPT_USE_EMBEDDED_CONNECTION, NULL);
  166.  
  167.             mysql_real_connect(myData, NULL,NULL,NULL, NULL, 0,NULL,0);
  168.  
  169.             /* Creamos la fuente */
  170.             HFONT hfont1 = CreateFont(-11, 0, 0, 0, 400, FALSE, FALSE, FALSE, 1, 400, 0, 0, 0, ("Ms Shell Dlg 2"));
  171.             /* Creamos el botón */
  172.             HWND hCtrl1_1 = CreateWindowEx(0, "BUTTON", ("Aceptar"), WS_VISIBLE | WS_CHILD | WS_TABSTOP | BS_PUSHBUTTON, 567, 380, 95, 24, hWnd, (HMENU)IDC_OK, hInst, 0);
  173.             /* Asignamos la fuente al botón */
  174.             SendMessage(hCtrl1_1, WM_SETFONT, (WPARAM)hfont1, FALSE);
  175.         }
  176.  
  177.     case WM_COMMAND:
  178.         wmId    = LOWORD(wParam);
  179.         wmEvent = HIWORD(wParam);
  180.         // Parse the menu selections:
  181.         switch (wmId)
  182.         {
  183.         case IDC_OK:
  184.             {
  185.                 mysql_query(myData,"CREATE DATABASE prueba");
  186.                 break;
  187.             }
  188.         case IDM_ABOUT:
  189.             DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About);
  190.             break;
  191.         case IDM_EXIT:
  192.             DestroyWindow(hWnd);
  193.             break;
  194.         default:
  195.             return DefWindowProc(hWnd, message, wParam, lParam);
  196.         }
  197.         break;
  198.     case WM_PAINT:
  199.         hdc = BeginPaint(hWnd, &ps);
  200.         // TODO: Add any drawing code here...
  201.         EndPaint(hWnd, &ps);
  202.         break;
  203.     case WM_DESTROY:
  204.  
  205.         mysql_close(myData);
  206.         mysql_library_end();
  207.  
  208.         PostQuitMessage(0);
  209.         break;
  210.     default:
  211.         return DefWindowProc(hWnd, message, wParam, lParam);
  212.     }
  213.     return 0;
  214. }
  215.  
  216. // Message handler for about box.
  217. INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
  218. {
  219.     UNREFERENCED_PARAMETER(lParam);
  220.     switch (message)
  221.     {
  222.     case WM_INITDIALOG:
  223.         return (INT_PTR)TRUE;
  224.  
  225.     case WM_COMMAND:
  226.         if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)
  227.         {
  228.             EndDialog(hDlg, LOWORD(wParam));
  229.             return (INT_PTR)TRUE;
  230.         }
  231.         break;
  232.     }
  233.     return (INT_PTR)FALSE;
  234. }
  235.  
  236.