You are on page 1of 10

C Programming with

Database

Speaker: Guo-Heng Luo ( 羅國亨 )


email: lasifu@gmail.com

Department of Computer and Information Science


National Chiao Tung University, Hsinchu 300,
Taiwan, R.O.C
TEL: 03-5712121 Ext. 59265, 56631
FAX: 03-5721490

111/02/05 1
Using MySQL DB by C through SQL
• MYSQL
– a data structure hold the information about database
• mysql_init
– Gets or initializes a MYSQL structure
• mysql_real_connect
– Connect to MySQL server
• mysql_select_db
– Choose database

111/02/05 2
Using MySQL DB by C through SQL
• mysql_query
– Execute query
• mysql_store_result
– Store result to data structure
• mysql_fetch_row
– Get a row from the query result(one by one)

111/02/05 3
Using MySQL DB by C through SQL
• MYSQL *mysql_real_connect()
– MYSQL *mysql
– const char *host
– const char *user
– const char *passwd
– const char *db || NULL
– unsigned int port || 0
– const char *unix_socket || NULL
– unsigned long client_flag || 0 || CLIENT_SSL…etc.

111/02/05 4
Using MySQL DB by C through SQL
#include <unistd.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <mysql/mysql.h>
#include <signal.h>
#include <errno.h>
#include <syslog.h>

111/02/05 5
Using MySQL DB by PHP through SQL
MYSQL mysql;
main(){
char host[32]="dbhome.cs.nctu.edu.tw“;
char user[32]="yourname";
char passwd[32]="yourpass";
char dbname[32]="ghluo_cs_i2cs";

mysql_init(&mysql);

mysql_real_connect(&mysql,host,user,passwd,NULL,0,NULL,0)
;

mysql_select_db(&mysql, dbname);

MYSQL_ROW m_row;
MYSQL_RES *m_res;
111/02/05 6
Using MySQL DB by PHP through SQL
char sql[1024];
sprintf(sql,"select * from members");

mysql_query(&mysql,sql);

m_res = mysql_store_result(&mysql);

while(m_row = mysql_fetch_row(m_res))
{
printf("id=%s, name=%s\n",m_row[0],m_row[1]);
}
mysql_free_result(m_res);

mysql_close(&mysql);
return 0;
}
111/02/05 7
Example connect2.c
• gcc -g connect2.c -L/usr/lib/mysql -lmysqlclient -lz
-o connect2
• ./connect2

111/02/05 8
C Example

111/02/05 9
Reference
• http://dev.mysql.com/doc/refman/4.1/en/building-clie
nts.html

111/02/05 10

You might also like