Skip to content

Instantly share code, notes, and snippets.

@surinoel
Last active September 9, 2019 06:15
Show Gist options
  • Save surinoel/29f5cfe613d5af5f3ef0a3b144a0f10f to your computer and use it in GitHub Desktop.
Save surinoel/29f5cfe613d5af5f3ef0a3b144a0f10f to your computer and use it in GitHub Desktop.
#include <mysql.h>
#include <stdio.h>
int main(void) {
MYSQL *conn = mysql_init(NULL);
if (conn == NULL) {
printf("%s\n", mysql_error(conn));
return -1;
}
if (mysql_real_connect(conn, "192.168.0.93", "sn", "8993", "mydb", 0, NULL, 0) == NULL) {
printf("%s\n", mysql_error(conn));
mysql_close(conn);
return -1;
}
#if 0
if (mysql_query(conn, "CREATE DATABASE testdb")) {
cout << mysql_error(conn) << '\n';
mysql_close(conn);
return -1;
}
#endif
// 성공했을 때 0을 반환
if(mysql_query(conn, "set names euckr")) {
printf("%s\n", mysql_error(conn));
mysql_close(conn);
return -1;
}
int id;
printf("user id : ");
scanf("%d", &id);
char name[10];
printf("user name : ");
scanf("%s", name);
char addr[20];
printf("user addr : ");
scanf("%s", addr);
char query[200];
sprintf_s(query, "INSERT INTO addressbook(id, name, address) VALUES ('%d', '%s', '%s')", id, name, addr);
if (mysql_query(conn, query)) {
printf("error\n");
mysql_close(conn);
return -1;
}
if (mysql_query(conn, "INSERT INTO addressbook VALUES(3, '유영재', '서울시 강서구 화곡동')"))
{
printf("error\n");
mysql_close(conn);
return -1;
}
// 성공했을 때 0을 반환
if (mysql_query(conn, "SELECT * FROM addressbook")) {
printf("error\n");
mysql_close(conn);
return -1;
}
MYSQL_RES *res = mysql_store_result(conn);
if (res == NULL) {
printf("%s\n", mysql_error(conn));
mysql_close(conn);
return -1;
}
int num_fields = mysql_num_fields(res);
MYSQL_ROW row;
while ((row = mysql_fetch_row(res))) {
for (int i = 0; i < num_fields; i++) {
printf("%s ", row[i]);
}
}
mysql_free_result(res);
mysql_close(conn);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment