您的位置:首页 > 编程语言 > C语言/C++

Ubuntu下用C语言连接MySql——实现增删改查排序

2013-12-29 09:44 567 查看
1.安装mysql服务器,客户端 sudo apt-get install mysql-server mysql-client,这样就能建数据库了。
2.安装mysql的开发包——— sudo apt-get insatll libmysql++-dev 获得/usr/include/mysql/下的头文件接口和/usr/lib/mysql/下的so库 (网上也有很多说用命令sudo apt-get install libmysqlclient15-dev)
都行吧。 不装开发包,就不能编程。



3.现在可以新建一个学生管理系统——dbStu,并且dbStu设置为当前数据库





4.建立tbStu表格,利用sql语句create table .....太长了,看图吧。再用describe tbStu 可以显示表格的属性



5.表格建好了就插入记录吧。下面插入第一条记录,插入多条后,用select语句展示表格数据。
.


.


6.好了,开始C语言编程了。
#include <stdio.h>
#include <stdlib.h>
#include <string.h> // 用于支持strlen
#include <mysql.h>

MYSQL* pConn;       // 连接对象       
MYSQL_RES* pRes;    // 结果集
MYSQL_ROW  Row;     // 记录,注意不是MYSQL_ROW * 指针类型

struct Stu          // 学生结构体
{
   int id;          // 学号
   char name[10];   // 姓名
   int score;       // 分数
};

/* 增加(插入)一条记录 */
void add_record()
{
   char cmd[1024] = {0};
   int i = 0, numFields = 0;
   int ret = 0;
   struct Stu stu; 
   
   printf("请输入学生id:");
   scanf("%d", &stu.id);
   
   printf("请输入学生姓名:");
   scanf("%s", stu.name);
 
   printf("请输入学生分数:");
   scanf("%d", &stu.score);
   // 强大的sprintf为用户减少输入 ,避免让用户输入完整的命令,而只需要记录的数据输入
   sprintf(cmd, "insert into tbStu(id,name,score) values(%d,'%s',%d)",stu.id,stu.name,stu.score);     
   
   ret = mysql_real_query(pConn, cmd, (unsigned int)strlen(cmd));
   if(! ret)  // ret = 0是表示正确
   {
      // 打印受到影响的行的个数
      printf("Inserted by %lu rows\n",(unsigned long)mysql_affected_rows(pConn));
   }
   else  // ret != 0 表示出错
   {
      // 打印出错及相关信息
      fprintf(stderr, "Insert error %d:%s\n", mysql_errno(pConn), mysql_error(pConn));

   }
//   mysql_free_result(pRes);
   return ;
}

/* 删除一条记录 */
void del_record()
{
   int i = 0,numFields = 0;
   int ret = 0;
   char cmd[1024] = {0};
   int delId;

   printf("请输入要删除的学生id:");
   scanf("%d",&delId);
   sprintf(cmd,"delete from tbStu where id = %d",delId);

   ret = mysql_real_query(pConn, cmd, (unsigned int)strlen(cmd));
   if(! ret)  // ret = 0是表示正确
   {
      // 打印受到影响的行的个数
      printf("Deleted by %lu rows\n",(unsigned long)mysql_affected_rows(pConn));
   }
   else
   {
      // 打印出错及相关信息
      fprintf(stderr, "Deleted error %d:%s\n", mysql_errno(pConn), mysql_error(pConn));
       
   }
//   mysql_free_result(pRes);
   return ;
}
/* 修改一条key指定的记录 */
void mod_record()
{
   int i = 0,numFields = 0;
   int ret = 0;
   char cmd[1024] = {0};
   struct Stu stu; 
   int modId;
   
   printf("请输入要修改的学生id:");
   scanf("%d", &modId);
   
   printf("请输入该学生的新id:");
   scanf("%d", &stu.id);

   printf("请输入该学生的新姓名:");
   scanf("%s", stu.name);
 
   printf("请输入学生新分数:");
   scanf("%d", &stu.score);

   sprintf(cmd,"update tbStu set id=%d,name='%s',score=%d where id=%d",stu.id,stu.name,stu.score,modId);// 注意%s两边有小引号哦
   
   ret = mysql_real_query(pConn, cmd, (unsigned int)strlen(cmd));
   if(! ret)  // ret = 0是表示正确
   {
      // 打印受到影响的行的个数
      printf("Updated by %lu rows\n",(unsigned long)mysql_affected_rows(pConn)  );
   }
   else
   {
      // 打印出错及相关信息
      fprintf(stderr, "Updated error %d:%s\n", mysql_errno(pConn), mysql_error(pConn));

   }
//   mysql_free_result(pRes);
   return ;
}

/* 打印整张表格 */
void display_record()
{
   int i = 0,numFields = 0;
   int ret = 0;
   char cmd[1024] = {0};
     
   sprintf(cmd,"select* from tbStu");  // 整张表查找
   ret = mysql_real_query(pConn, cmd, (unsigned int)strlen(cmd));
   if(ret) // 出错
   {
      printf("select error:%s\n", mysql_error(pConn));
   }
   else
   {
      pRes = mysql_store_result(pConn);
      if(pRes)
      {
         printf("一共%d行\n",(int)mysql_num_rows(pRes));
         numFields = mysql_num_fields(pRes); // 获取列的个数
         while(Row = mysql_fetch_row(pRes))      // 取出每条记录
         {
            for(i = 0; i < numFields; i++)
            {
                printf("%s\t",Row[i]?Row[i]:NULL);
            }
            printf("\n");
         }
         if(mysql_errno(pConn))
         {
           fprintf(stderr, "Retrieve error:%s\n", mysql_error(pConn)); 
         }
      }

   }
//    mysql_free_result(pRes);
    return ;
   
   
}

/* 按成绩降序排序 */
void sort_desc()
{
   int i = 0, numFields = 0;
   int ret = 0;
   char cmd[1024] = {0};

   sprintf(cmd,"select* from tbStu order by score desc");
   
   ret = mysql_real_query(pConn, cmd, (unsigned int)strlen(cmd));

   if(ret) // 出错
   {
      printf("select error:%s\n", mysql_error(pConn));
   }
   else
   {
      pRes = mysql_store_result(pConn);
      if(pRes)
      {
         printf("一共%d行\n",(int)mysql_num_rows(pRes));
         numFields = mysql_num_fields(pRes); // 获取列的个数
         while(Row = mysql_fetch_row(pRes))      // 取出每条记录
         {
            for(i = 0; i < numFields; i++)
            {
                printf("%s \t",Row[i]?Row[i]:NULL);
            }
            printf("\n");
         }
         if(mysql_errno(pConn))
         {
           fprintf(stderr, "Retrieve error:%s\n", mysql_error(pConn)); 
         }
      }
   }

//   mysql_free_result(pRes);

   return ;

}

int main()
{  
    pConn = mysql_init(NULL);
    if(!pConn)
    {
       printf("pConn初始化失败\n");
       return -1; 
    }
    else
    {
       printf("pConn初始化成功\n");
    }

    pConn = mysql_real_connect(pConn, "localhost", "root", "xiaobinge", "dbStu", 0, NULL, 0);
    if(!pConn)
    {
        printf("pConn连接失败\n");
        return -1;
    }
    else
    {
        printf("pConn连接成功\n");
    }

    while(1)
    {
       printf("******1.增加一条记录***********\n");
       printf("******2.删除一条记录***********\n");
       printf("******3.修改一条记录***********\n");
       printf("******4.查询现在的所有记录*****\n");
       printf("******5.按成绩降序排序*********\n");
       printf("******0.退出程序***************\n");
       printf("请输入操作选项编号0~4:");
       int id;
       scanf("%d",&id);
       switch(id)
       {
           case 0:
               {
                  printf("Bye");
                  mysql_free_result(pRes);
                  mysql_close(pConn);
                  return 0;
               }
           case 1:
               {
                  add_record();
                  break;
               }
           case 2:
               {
                   del_record();
                   break;
               }
           case 3:
               {
                   mod_record();
                   break;
               }
           case 4:
               {
                   display_record();
                   break;
               }
           case 5:
               {
                   sort_desc();
                   break;
               }
       }// end switch
     
    }// end while    

   return 0;
}



7.只有一个.c文件,所以直接用gcc 编译,不需要麻烦的make。gcc adus.c -o adus -I /usr/include/mysql/ -L /usr/lib/mysql/ -l mysqlclient
分别是大写的i,表示INCLUDE,大写的L,表示LINK,小写的L,表示link 一个库


注意:1.c89 里的C语言不能出现bool变量,编译不过的。
2.mysql_free_result(pRes); 不能重复调用。(这个也没仔细测试,反正写在每个操作的return 之前,偶尔有时会提示,出现多次释放指针问题)
8.运行:
// 测试菜单选项1:添加记录





// 测试菜单选项2:删除记录



// 测试菜单选项3:修改一条记录



// 测试菜单选项5:排序

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: