zoukankan      html  css  js  c++  java
  • Ubuntu下用C直接操作Mysql数据库的方法

    ubuntu下用C直接操作Mysql数据库的方法

    转载自:http://hi.baidu.com/wdr_cloud/item/7d87e609102b24943d42e251

    以下内容仅供个人学习之用,切勿挪用他途。



    首先安装好mysql,一般情况下是没有mysql.h这个头文件的。

    sudo apt-get install mysql-server mysql-client
    sudo apt-get install libmysqlclient15-dev

    安装好后,用find查找mysql.h的路径

    example:/usr/include/mysql/mysql.h(我的是在这个路径下)

    1,使用c语言操作mysql之前,先在mysql里头创建一个数据库,一个表,在表里头添加数据如下:
          

    创建数据库,库名为wang:
    mysql>create database wang;
    创建表,表名为:
    mysql>use wang;
    mysql>create table stu(sno int,fname varchar(20),age int);

    添加数据:

    insert into stu values(1,"dingding",24);

    insert into stu values(2,"wang",22);

    2 ,下面进行具体的操作

    插入:insert.c

    #i nclude <stdio.h>
    #i nclude <stdlib.h>
    #i nclude "/usr/include/mysql/mysql.h" 


    int main(int argc, char *argv[])
    {
    MYSQL my_connection;

    int res;

    mysql_init(&my_connection);

    if (mysql_real_connect(&my_connection, "localhost", "root", "","wang",0,NULL,CLIENT_FOUND_ROWS))
    {
        printf("Connection success\n");
        res = mysql_query(&my_connection, "insert into stu values(3,'apple',21)");

        if (!res)
        {
            printf("Inserted %lu rows\n",(unsigned long)mysql_affected_rows(&my_connection));
        }
        else
        {
            fprintf(stderr, "Insert error %d: %s\n",mysql_errno(&my_connection),mysql_error(&my_connection));
        }
        mysql_close(&my_connection);
    }

    else
    {
        fprintf(stderr, "Connection failed\n");

        if (mysql_errno(&my_connection))
        {
            fprintf(stderr, "Connection error %d: %s\n",mysql_errno(&my_connection),mysql_error(&my_connection));
            }
    }
        return EXIT_SUCCESS;
    }

    编译:

    gcc -o insert insert.c -l mysqlclient

    ./insert

    Connection Success
    Inserted 1 rows

    更新:update

    我们只要把上面的代码中的

    res = mysql_query(&my_connection, "insert into stu values(3,'apple',21)");

    换成

    res = mysql_query(&my_connection, "update stu set age=19 where sno>2 ");

    即可
  • 相关阅读:
    【技巧总结】公开漏洞学习
    【 Keepalived 】Nginx or Http 主-主模式
    【 Keepalived 】Nginx or Http 主-备模式
    【 转 】Keepalived工作原理
    【 总结 】crontab 使用脚本及直接获取HTTP状态码
    【 总结 】linux中test命令详解
    【 总结 】Tcp Keepalive 和 HTTP Keepalive 详解
    【 Linux 】I/O工作模型及Web服务器原理
    【 Ngnix 】配置路径转发至后端Apache多台虚拟主机
    【 Linux】脚本导入格式
  • 原文地址:https://www.cnblogs.com/techstone/p/3321356.html
Copyright © 2011-2022 走看看