#include <stdio.h>
#include <string.h>
#include <mysql.h>
int main()
{
MYSQL mysql;
MYSQL_RES *res;
MYSQL_ROW row;
char *query;
int t;
mysql_init(&mysql);
/*connection*/
if(!mysql_real_connect(&mysql,"localhost","root","","test",0,NULL,0)){
printf("Connect failed\n");
}else{
printf("Connect successful\n");
}
/*select*/
query="select * from t1;";
if(mysql_real_query(&mysql,query,(unsigned int)strlen(query))==0){
printf("query successful\n");
}else{
printf("query failed\n");
}
res=mysql_store_result(&mysql);
while(row=mysql_fetch_row(res)){
for(t=0;t<mysql_num_fields(res);t++)
{
printf("%s\t",row[t]);
}
}
/*create table*/
/* query="create table t2(name char(15),age int);";
if(mysql_real_query(&mysql,query,(unsigned int)strlen(query))==0){
printf("create table successful\n");
}else{
printf("create table failed\n");
}
*/
/*insert*/
/* query="insert into t1(name,age) values ('zhang',32);";
if(mysql_real_query(&mysql,query,(unsigned int)strlen(query))==0){
printf("Insert successful\n");
}else{
printf("Insert failed\n");
}
*/
/*delete*/
/* query="delete from t1 where age=20;";
if(mysql_real_query(&mysql,query,(unsigned int)strlen(query))==0){
printf("Delete successful\n");
}else{
printf("Delete failed\n");
}
*/
/*update*/
/* query="update t1 set age=100 where name='wa';";
if(mysql_real_query(&mysql,query,(unsigned int)strlen(query))==0){
printf("Update successful\n");
}else{
printf("Update failed\n");
}
*/
mysql_close(&mysql);
return 0;
}
安装
mysql-server-5.1.73-3.el6_5.x86_64
mysql-5.1.73-3.el6_5.x86_64
mysql-connector-odbc-5.1.5r1144-7.el6.x86_64
mysql-devel-5.1.73-3.el6_5.x86_64
mysql-libs-5.1.73-3.el6_5.x86_64
编译
gcc -o sqlconnect sqlconnect.c -I/usr/include/mysql -L/usr/lib64/mysql -lmysqlclient