Advertisement
Guest User

Untitled

a guest
Jul 20th, 2017
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.00 KB | None | 0 0
  1. // Run a insert operation to store a new record
  2. int insert() {
  3.     // Connection stuff
  4.     const char  *conninfo;
  5.     PGconn      *conn;
  6.     PGresult    *res;
  7.    
  8.     // User data
  9.     char *name;
  10.     char *last_p;
  11.     char *last_m;
  12.     char *birth;
  13.     int phone;
  14.    
  15.     // Query parameters
  16.     int         paramFormats[5] = {0,0,0,0,1};
  17.     int         paramLengths[5];
  18.     const char  *userData[5];
  19.    
  20.     // Try to connect to the server
  21.     conninfo = "host=pghost user=user password=pass dbname=db";
  22.     conn = PQconnectdb( conninfo );
  23.     if( PQstatus( conn ) != CONNECTION_OK ) {
  24.         fprintf( stderr, "Error de conexion con la base de datos: %s", PQerrorMessage( conn ) );
  25.         PQfinish( conn );
  26.         exit( 1 );
  27.     }
  28.    
  29.     // Get the user data from standard input
  30.     printf( "Nombre: " );
  31.     scanf( "%s", &name );
  32.     printf( "Apellido Paterno: " );
  33.     scanf( "%s", &last_p );
  34.     printf( "Apellido Materno: " );
  35.     scanf( "%s", &last_m );
  36.     printf( "Fecha de Nacimiento ( yyyy-mm-dd ): " );
  37.     scanf( "%s", &birth );
  38.     printf( "Numero de Telefono: " );
  39.     scanf( "%d", phone );
  40.    
  41.     // Convert all to binary
  42.     userData[0] = name;
  43.     userData[1] = last_p;
  44.     userData[2] = last_m;
  45.     userData[3] = birth;
  46.     userData[4] = (char *) htonl( (uint32_t) phone );
  47.     paramLengths[0] = strlen( name );
  48.     paramLengths[1] = strlen( last_p );
  49.     paramLengths[2] = strlen( last_m );
  50.     paramLengths[3] = strlen( birth );
  51.     paramLengths[4] = sizeof( phone );
  52.    
  53.    
  54.     // Insert it on the database
  55.     res = PQexecParams( conn,
  56.                 "INSERT INTO directorio (nombre, apPaterno, apMaterno, festejo, telefono) VALUES ($1, $2, $3, $4, $5::bigint )",
  57.                 5,       //
  58.                 NULL,    // let the backend deduce param type
  59.                 userData,
  60.                 paramLengths,
  61.                 paramFormats,
  62.                 0 );
  63.     if( PQresultStatus( res ) != PGRES_COMMAND_OK ) {
  64.         fprintf( stderr, "Error al guardar el registro: %s", PQerrorMessage( conn ) );
  65.         PQclear( res );
  66.         PQfinish( conn );
  67.         exit( 1 );
  68.     } else {
  69.         printf( "\n-> El registro fue creado exitosamente\n" );
  70.         PQclear( res );
  71.         PQfinish( conn );
  72.         return 0;
  73.     }
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement