[C con Clase] Mostrar datos de MySql con Win Api

Salvador Pozo salvador en conclase.net
Dom Abr 8 00:16:51 CEST 2012


El pasado 2012-04-07 10:13:46, Robertti escribió:
 
R> Hola Salvador,
R> primeramente quiero agradecerte que me contestaras tan rapidamente. Pero, debo confesarte que me he perdido, he probado de todas las formas posibles como yo lo entiendo, pero no soy capaz de estructurar una consulta a mi MySql y luego imprimirlo en pantalla. Te pido, si no es mucha molestia, y si puede ser, me escribar los códigos en las zonas de este que te envío donde deben ir cada declaración, por favor...

Bueno, no es un ejemplo completo, pero espero que te sirva de guía.

----8<------
#include <windows.h>
#include <mysql/mysql.h>

using namespace std;

#define CM_DIALOGO 1000

typedef struct DATOS {
      MYSQL *myData;
      // Otros datos...
} UNALIGNED *PDATOS;

/*  Declare Windows procedure  */
LRESULT CALLBACK WindowProcedure (HWND, UINT, WPARAM, LPARAM);
BOOL CALLBACK DlgProcedure(HWND hDlg, UINT msg, WPARAM wParam, LPARAM lParam);

/*  Make the class name into a global variable  */
char szClassName[ ] = "WindowsApp";

int WINAPI WinMain (HINSTANCE hThisInstance,
                   HINSTANCE hPrevInstance,
                   LPSTR lpszArgument,
                   int nFunsterStil)

{
   HWND hwnd;               /* This is the handle for our window */
   MSG messages;            /* Here messages to the application are saved */
   WNDCLASSEX wincl;        /* Data structure for the windowclass */
   // Estructura para disponer de datos durante todo el programa.
   DATOS datos;

   datos.myData = mysql_init(0);

   /* The Window structure */
   wincl.hInstance = hThisInstance;
   wincl.lpszClassName = szClassName;
   wincl.lpfnWndProc = WindowProcedure;      /* This function is called by windows */
   wincl.style = CS_DBLCLKS;                 /* Catch double-clicks */
   wincl.cbSize = sizeof (WNDCLASSEX);

   /* Use default icon and mouse-pointer */
   wincl.hIcon = LoadIcon (NULL, IDI_APPLICATION);
   wincl.hIconSm = LoadIcon (NULL, IDI_APPLICATION);
   wincl.hCursor = LoadCursor (NULL, IDC_ARROW);
   wincl.lpszMenuName = NULL;                 /* No menu */
   wincl.cbClsExtra = 0;                      /* No extra bytes after the window class */
   wincl.cbWndExtra = 0;                      /* structure or the window instance */
   /* Use Windows's default color as the background of the window */
   wincl.hbrBackground = (HBRUSH) COLOR_BACKGROUND;

   /* Register the window class, and if it fails quit the program */
   if (!RegisterClassEx (&wincl)) return 0;

   /* The class is registered, let's create the program*/
   hwnd = CreateWindowEx(
          0,                   /* Posibilidades de variación */
          szClassName,     /* Nombre de la clase */
          "Titulo",            /* Texto del título */
          WS_OVERLAPPEDWINDOW &
          ~WS_THICKFRAME &
          ~WS_MAXIMIZEBOX,     /* Tipo por defecto */
          CW_USEDEFAULT,       /* Windows decide la posición */
          CW_USEDEFAULT,       /* donde se coloca la ventana */
          504,                 /* Ancho */
          355,                 /* Alto en pixels */
          HWND_DESKTOP,        /* La ventana es hija del escritorio */
          NULL,                /* Sin menú */
          hThisInstance,       /* Manipulador de instancia */
          (void*)&datos        /* Datos de creación de ventana */
   );

   /* Make the window visible on the screen */
   ShowWindow (hwnd, nFunsterStil);

   /* Run the message loop. It will run until GetMessage() returns 0 */
    while(TRUE == GetMessage(&messages, NULL, 0, 0))
   {
       /* Translate virtual-key messages into character messages */
       TranslateMessage(&messages);
       /* Send message to WindowProcedure */
       DispatchMessage(&messages);
   }

   if(datos.myData) mysql_close(datos.myData);
   /* The program return-value is 0 - The value that PostQuitMessage() gave */
   return messages.wParam;
}


/*  This function is called by the Windows function DispatchMessage()  */

LRESULT CALLBACK WindowProcedure (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
   static PDATOS datos;
    /* dtos de conexion*/
   char *host = "localhost";
   char *user = "root";
   char *pass = "sagitario"; //"Tokage2008";
   char *db = "prueba"; //"test";
   MYSQL_RES *res;
   MYSQL_ROW row;

   switch (message)                  /* handle the messages */
   {
      case WM_CREATE:
          datos = (DATOS*)(((LPCREATESTRUCT) lParam)->lpCreateParams);
          if(!mysql_real_connect(datos->myData, host, user, pass, db, MYSQL_PORT, NULL, 0)) {
              // No se puede conectar con el servidor en el puerto especificado.
              MessageBox(hwnd, "Imposible conectar con servidor mysql.", "Error", MB_OK);
              return -1;
          }
          mysql_query(datos->myData, "SELECT * FROM prueba.users LIMIT 1");
          if((res = mysql_store_result(datos->myData))) {
             // Procesar resultados
             row = mysql_fetch_row(res);
             // Mostrar cada campo:
             MessageBox(hwnd, row[1], row[2], MB_OK);
             // Liberar el resultado de la consulta:
             mysql_free_result(res);
          }
          return 0;

      case WM_COMMAND:
          switch(LOWORD(wParam)) {
             case CM_DIALOGO:
                DialogBoxParam(GetModuleHandle(0), "Dialogo", hwnd, DlgProcedure, (LPARAM)datos);
                break;
          }
          break;
       case WM_DESTROY:
           PostQuitMessage (0);       /* send a WM_QUIT to the message queue */
           break;
       default:                      /* for messages that we don't deal with */
           return DefWindowProc (hwnd, message, wParam, lParam);
   }

   return 0;
}

BOOL CALLBACK DlgProcedure(HWND hDlg, UINT msg, WPARAM wParam, LPARAM lParam)
{
   static PDATOS datos;
   MYSQL_RES *res;
   MYSQL_ROW row;

   switch (msg)                  /* manipulador del mensaje */
   {
       case WM_INITDIALOG:
          datos = (DATOS *)lParam;
          if(mysql_query(datos->myData, "SELECT * FROM gente LIMIT 1")) {
              printf("ERROR: %d\n", mysql_error(datos->myData));
          }
          res = mysql_store_result(datos->myData);
          if(res) {
             // Procesar resultados
             row = mysql_fetch_row(res);
             // Hacer algo con los datos leidos...
             // Liberar el resultado de la consulta:
             mysql_free_result(res);
          }
          return TRUE;
   }
   return FALSE;
}
----8<------

Hasta pronto.

-- 
Salvador Pozo (Administrador)
mailto:salvador en conclase.net


Más información sobre la lista de distribución Cconclase