44
42

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

CでMySQLにアクセスする

Last updated at Posted at 2015-01-06

#概要
MySQLのCドライバを使って
MySQLにアクセスするサンプルを作りましたので、そのソースと手順などを共有したいと思います。

#開発環境構築
MySQLとドライバをインストールします。

yum -y update
yum -y install mysql-devel mysql-server gcc
service mysqld start

Ubuntu(docker ubuntu:14.10)

apt-get update
apt-get -y upgrade
apt-get -y install libmysqlclient-dev mysql-server gcc
/etc/init.d/mysql start

##テスト用データの入力
テスト用なので適当にデータを入れてください。

mysql -uroot
create database db_test;
use db_test
create table tb_test(id int,name varchar(256));
insert into tb_test(id,name) values(1,"aaa");
insert into tb_test(id,name) values(2,"bbb");
insert into tb_test(id,name) values(3,"ccc");
exit

#MySQLへアクセス

mysql.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <mysql/mysql.h>
int main(void){
  MYSQL *conn     = NULL;
  MYSQL_RES *resp = NULL;
  MYSQL_ROW row;
  char sql_str[255];
  char *sql_serv  = "localhost";
  char *user      = "root";
  char *passwd    = "";
  char *db_name   = "db_test";
  
  memset( &sql_str[0] , 0x00 , sizeof(sql_str) );

  // mysql接続
  conn = mysql_init(NULL);
  if( !mysql_real_connect(conn,sql_serv,user,passwd,db_name,0,NULL,0) ){
    // error
    exit(-1);
  }
  
  // クエリ実行
  snprintf( &sql_str[0] , sizeof(sql_str)-1 , "select * from tb_test" );
  if( mysql_query( conn , &sql_str[0] ) ){
    // error
    mysql_close(conn);
    exit(-1);
  }
  
  // レスポンス
  resp = mysql_use_result(conn);
  while((row = mysql_fetch_row(resp)) != NULL ){
    printf( "%d : %s\n" , atoi(row[0]) , row[1] );
  }
  
  // 後片づけ
  mysql_free_result(resp);
  mysql_close(conn);
  return 0;
}

##コンパイル、実行
「/usr/lib64/mysql/」の部分はfind /-name "libmysqlclient.so"等で
ライブラリの配置場所を探してパスを指定します。

gcc -Wall -o mysql mysql.c -lmysqlclient -L/usr/lib64/mysql/
./mysql
1 : aaa
2 : bbb
3 : ccc
44
42
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
44
42

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?