1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
| #include <stdio.h>
#include <stdlib.h>
#include <mysql/mysql.h>
#ifdef WIN32
#include <winsock.h>
#elif defined(linux)
#endif
MYSQL *
do_mysql_connect (char *host_name, char *user_name, char *password,
char *db_name, unsigned int port_num, char *socket_name,
unsigned int flags)
{
MYSQL *conn; /* pointer to connection handler */
conn = mysql_init (NULL); /* allocate, initialize connection handler */
if (conn == NULL)
{
fprintf (stderr, "mysql_init() failed\n");
return (NULL);
}
if (mysql_real_connect (conn, host_name, user_name, password,
db_name, port_num, socket_name, flags) == NULL)
{
fprintf (stderr, "mysql_real_connect() failed:\nError %u (%s)\n",
mysql_errno (conn), mysql_error (conn));
return (NULL);
}
return (conn); /* connection is established */
}
void
print_infos (MYSQL_RES * res, int num_rows)
{
MYSQL_ROW row;
unsigned int num_fields;
unsigned int j = 0;
unsigned long *lengths;
num_fields = mysql_num_fields (res);
while ((row = mysql_fetch_row (res)))
{
lengths = mysql_fetch_lengths (res);
int i;
for (i = 0; i < num_fields; i++)
{
printf ("[%.*s] ", (int) lengths[i], row[i] ? row[i] : "NULL");
}
printf ("\n");
j++;
}
}
int
main ()
{
char hostname[] = "somehost.com";
char user_name[] = "someusername";
char password[] = "somepass";
char db_name[] = "my_db";
unsigned int port = 64000, num_rows, i;
char query[1024];
MYSQL *conn = NULL;
MYSQL_RES *res = NULL;
conn = do_mysql_connect (hostname, user_name, password, db_name,
port, NULL, 0);
mysql_query (conn, "select champ1,champ2 from table");
res = mysql_store_result (conn);
if (res == NULL)
{
perror ("res is NULL");
return EXIT_FAILURE;
}
num_rows = mysql_num_rows (res);
print_infos (res, num_rows);
snprintf (query, sizeof (query), "UPDATE table SET champs12 = 3");
mysql_query (conn, query);
mysql_free_result (res);
mysql_close (conn);
return EXIT_SUCCESS;
} |
Partager