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 ");

    即可
  • 相关阅读:
    [2018福大至诚软工助教]原型设计+用户规格说明书小结
    高等数理逻辑大作业
    [2018福大至诚软工助教]测试与优化小结
    [2018福大至诚软工助教]结对项目小结
    BETA 版冲刺前准备
    Alpha冲刺之事后诸葛亮
    Alpha 冲刺 (10/10)
    Alpha 冲刺 (9/10)
    Alpha 冲刺 (8/10)
    Alpha 冲刺 (7/10)
  • 原文地址:https://www.cnblogs.com/techstone/p/3321356.html
Copyright © 2011-2022 走看看