Linux C语言连接MySQL 增删改查操作

来源:互联网 发布:淘宝网大童长款皮衣 编辑:程序博客网 时间:2024/05/16 19:42
 编译语句 gcc -I/usr/include/mysql connect.c -L/usr/lib/mysql/ -lmysqlclient -o connect


参考文章:http://hi.baidu.com/156544632/item/ee98549621e46eb882d2956f

http://asyty.iteye.com/blog/1447092

mysql>create database cusemysql;
mysql>use cusemysql;
mysql>create table children(childno int not null unique,fname varchar(20),age int);
mysql>insert into children values(5,"hong",10);


#include <stdio.h>#include <stdlib.h>#include <mysql.h>MYSQL *conn_ptr;  MYSQL my_connection;MYSQL_RES *res_ptr;MYSQL_ROW sqlrow; int res;void show() {int i,j;conn_ptr = mysql_init(NULL);  conn_ptr = mysql_real_connect(conn_ptr, "localhost", "root","12345","cusemysql",0,NULL,CLIENT_FOUND_ROWS);  res = mysql_query(conn_ptr, "select childno,fname,age from children"); //查询语句          if (!res) {                       res_ptr = mysql_store_result(conn_ptr);             //取出结果集              if(res_ptr) {                               printf("show %lu Rows\n",(unsigned long)mysql_num_rows(res_ptr));                   j = mysql_num_fields(res_ptr);                          while((sqlrow = mysql_fetch_row(res_ptr)))  {   //依次取出记录                      for(i = 0; i < j; i++)                                 printf("%-10s\t", sqlrow[i]);              //输出                      printf("\n");                          }        }  } else {       printf("SELECT error\n");       }   }void insert() {res = mysql_query(&my_connection, "insert into children values(10,'Ann',5)");   if (!res) {       printf("Inserted %lu rows\n",(unsigned long)mysql_affected_rows(&my_connection));} else {       printf("insert error\n");   }}void update() {res = mysql_query(&my_connection, "update children set age=20 where childno = 10");   if (!res) {       printf("update success\n");} else {       printf("update error\n");       }}void delete() {res = mysql_query(&my_connection, "delete from children where childno = 10");   if (!res) {       printf("delete success\n");} else {       printf("delete error\n");       }}int main(int argc, char *argv[]) {mysql_init(&my_connection);int choose;int flag = 1;if (mysql_real_connect(&my_connection, "localhost", "root","12345","cusemysql",0,NULL,CLIENT_FOUND_ROWS)) {   printf("Connection success\n");} else {   printf("Connection failed\n");  if (mysql_errno(&my_connection))  {        printf("Connection error\n");        }}while(flag) {printf("\n------------------------------\n");printf("1. show children information\n");printf("2. add children information\n");printf("3. update children information\n");printf("4. delete children information\n");printf("5. quit\n");printf("------------------------------\n");scanf("%d",&choose);switch(choose) {case 1:show();break;case 2:insert();break;case 3:update();break;case 4:delete();break;case 5:flag = 0;break;}}mysql_close(&my_connection);printf("Good bye\n");    return EXIT_SUCCESS;}



0 0
原创粉丝点击