centos7测试mysql c api

来源:互联网 发布:软件部职责要求 编辑:程序博客网 时间:2024/05/22 03:17

搭建环境测试环境

mysql> create database cusemysql;Query OK, 1 row affected (0.00 sec)mysql> use cusemysql;Database changedmysql> create table children(childno int not null unique,fname varchar(20),age int);Query OK, 0 rows affected (0.00 sec)mysql> insert into children values(5,"花儿",10);Query OK, 1 row affected (0.00 sec)mysql> select * from children;+---------+-------+------+| childno | fname | age  |+---------+-------+------+|       5 | 花儿  |   10 |+---------+-------+------+1 row in set (0.03 sec)mysql>

c测试代码,这里的用户名和密码都是root,不是的请修改

#include <stdio.h>#include <stdlib.h>#include "mysql/mysql.h" int main(int argc, char *argv[]){    MYSQL my_connection;    int res;    mysql_init(&my_connection);    /*mysql_real_connect(&mysql,host,user,passwd,dbname,0,NULL,0) == NULL)*/    if (mysql_real_connect(&my_connection, "localhost", "root", "root","cusemysql",0,NULL,CLIENT_FOUND_ROWS))    {            printf("Connection success\n");        res = mysql_query(&my_connection, "insert into children values(11,'Anny',5)");        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;}

编译、执行

[root@localhost test]# gcc -o insert insert.c -L /usr/lib64/mysql -lmysqlclient
[root@localhost test]# ./a.out
Connection success
Inserted 1 rows

转载地址:http://blog.chinaunix.net/uid-20384806-id-1953971.html

原创粉丝点击