Skip to content

Instantly share code, notes, and snippets.

@noateden
Last active August 14, 2018 08:29
Show Gist options
  • Save noateden/f10226ea90ce4c5dc4466f602c2def72 to your computer and use it in GitHub Desktop.
Save noateden/f10226ea90ce4c5dc4466f602c2def72 to your computer and use it in GitHub Desktop.
c mysql example
#include "config.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <mysql.h>
int main(int argc, char **argv)
{
MYSQL *mysql = NULL;
mysql = mysql_init(mysql);
if (!mysql) {
puts("Init faild, out of memory?");
return EXIT_FAILURE;
}
if (!mysql_real_connect(mysql, /* MYSQL structure to use */
MYSQL_HOST, /* server hostname or IP address */
MYSQL_USER, /* mysql user */
MYSQL_PWD, /* password */
NULL, /* default database to use, NULL for none */
0, /* port number, 0 for default */
NULL, /* socket file or named pipe name */
CLIENT_FOUND_ROWS /* connection flags */ )) {
puts("Connect failed\n");
} else {
const char *query = "SELECT VERSION()";
if (mysql_real_query(mysql, query, strlen(query))) {
printf("Query failed: %s\n", mysql_error(mysql));
} else {
puts("Query OK");
}
}
/* Select query
const char *query = "SELECT * FROM `user`";
mysql_query(mysql, query);
MYSQL_RES *result = mysql_store_result(mysql);
if (result == NULL)
puts("Query error");
else
{
int totalrows = mysql_num_rows(result);
int numfields = mysql_num_fields(result);
printf("Number of row: %d\n", totalrows);
printf("Number of field: %d\n", numfields);
MYSQL_ROW row;
while((row = mysql_fetch_row(result)))
{
for(int i = 0; i < numfields; i++)
{
printf("%s\n", row[i]);
}
}
}
*/
/* Insert example
char *query = (char*)malloc(1024);
for(int i=0;i<10;i++)
{
sprintf(query, "INSERT INTO `user` VALUES('user%d')", i);
if (mysql_query(mysql, query) != 0)
puts("error");
else
puts("success");
}
*/
mysql_close(mysql);
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment