1. 程式人生 > >centos7測試mysql c api

centos7測試mysql c api

搭建環境測試環境

mysql> create database cusemysql;
Query OK, 1 row affected (0.00 sec)

mysql> use cusemysql;
Database changed

mysql> 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; }

編譯、執行

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

轉載地址:http://blog.chinaunix.net/uid-20384806-id-1953971.html