Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- int insert() {
- // Connection stuff
- const char *conninfo;
- PGconn *conn;
- PGresult *res;
- // User data
- char *name;
- char *last_p;
- char *last_m;
- char *birth;
- int *phone;
- // Query parameters
- int paramFormats[5];
- int paramLengths[5];
- const char *userData[5];
- // Try to connect to the server
- conninfo = "host=internal-db.s13296.gridserver.com user=db13296 password=valgrind17 dbname=db13296_tarea";
- conn = PQconnectdb( conninfo );
- if( PQstatus( conn ) != CONNECTION_OK ) {
- fprintf( stderr, "Error de conexion con la base de datos: %s", PQerrorMessage( conn ) );
- PQfinish( conn );
- exit( 1 );
- }
- // Get the user data from standard input
- printf( "Nombre: " );
- scanf( "%s", &name );
- printf( "Apellido Paterno: " );
- scanf( "%s", &last_p );
- printf( "Apellido Materno: " );
- scanf( "%s", &last_m );
- printf( "Fecha de Nacimiento ( yyyy-mm-dd ): " );
- scanf( "%s", &birth );
- printf( "Numero de Telefono: " );
- scanf( "%d", &phone );
- // Convert all to binary
- userData[0] = name;
- userData[1] = last_p;
- userData[2] = last_m;
- userData[3] = birth;
- userData[4] = (char *) htonl( (uint32_t) phone );
- paramFormats[0] = 0;
- paramFormats[1] = 0;
- paramFormats[2] = 0;
- paramFormats[3] = 0;
- paramFormats[4] = 1; // Binary format for the integer parameter
- paramLengths[0] = sizeof( name );
- paramLengths[1] = sizeof( last_p );
- paramLengths[2] = sizeof( last_m );
- paramLengths[3] = sizeof( birth );
- paramLengths[4] = sizeof( phone );
- // Insert it on the database
- res = PQexecParams( conn,
- "INSERT INTO directorio (nombre, apPaterno, apMaterno, festejo, telefono) VALUES ($1, $2, $3, $4, $5::bigint )",
- 5, /* params */
- NULL, /* let the backend deduce param type */
- userData,
- paramLengths,
- paramFormats,
- 0 );
- if( PQresultStatus( res ) != PGRES_COMMAND_OK ) {
- fprintf( stderr, "Error al guardar el registro: %s", PQerrorMessage( conn ) );
- PQclear( res );
- PQfinish( conn );
- exit( 1 );
- } else {
- printf( "\n-> El registro fue creado exitosamente\n" );
- PQclear( res );
- PQfinish( conn );
- return 0;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement