linux下使用c语言访问mySql数据库

1 篇文章 0 订阅
1 篇文章 0 订阅

数据库:

CREATE DATABASE test;

CREATE TABLE `test` (
    `id` int(11) NOT NULL auto_increment,

    PRIMARY KEY (`id`)
);

ALTER TABLE `test`

    ADD COLUMN `name` varchar(20);

代码:

/*
 ============================================================================
 Name        : mysql_test.c
 Author      :
 Version     :
 Copyright   : Your copyright notice
 Description : Hello World in C, Ansi-style
 ============================================================================
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <mysql/mysql.h>

MYSQL *g_conn; // mysql 连接
 MYSQL_RES *g_res; // mysql 记录集
 MYSQL_ROW g_row; // 字符串数组,mysql 记录行
 
#define MAX_BUF_SIZE 1024 // 缓冲区最大字节数

const char *g_host_name = "localhost";
const char *g_user_name = "root";
const char *g_password = "root";
const char *g_db_name = "test";
const unsigned int g_db_port = 3306;

void print_mysql_error(const char *msg) { // 打印最后一次错误
    if (msg)
        printf("%s: %s\n", msg, mysql_error(g_conn));
    else
        puts(mysql_error(g_conn));
}

int executesql(const char * sql) {
    /*query the database according the sql*/
    if (mysql_real_query(g_conn, sql, strlen(sql))) // 如果失败
        return -1; // 表示失败

    return 0; // 成功执行
}


int init_mysql() { // 初始化连接
    // init the database connection
    g_conn = mysql_init(NULL);

    /* connect the database */
    if(!mysql_real_connect(g_conn, g_host_name, g_user_name, g_password, g_db_name, g_db_port, NULL, 0)) // 如果失败
        return -1;

    // 是否连接已经可用
    if (executesql("set names utf8")) // 如果失败
        return -1;

    return 0; // 返回成功
}


int main(void) {
    puts("!!!Hello World!!!"); /* prints !!!Hello World!!! */

    if (init_mysql());
        print_mysql_error(NULL);

    char sql[MAX_BUF_SIZE];
    sprintf(sql, "INSERT INTO `test`(`name`) VALUES('testname')");

    if (executesql(sql))
        print_mysql_error(NULL);

    if (executesql("SELECT * FROM `test`")) // 句末没有分号
        print_mysql_error(NULL);

    g_res = mysql_store_result(g_conn); // 从服务器传送结果集至本地,mysql_use_result直接使用服务器上的记录集

    int iNum_rows = mysql_num_rows(g_res); // 得到记录的行数
    int iNum_fields = mysql_num_fields(g_res); // 得到记录的列数

    printf("共%d个记录,每个记录%d字段\n", iNum_rows, iNum_fields);

    puts("id\tname\n");

    while ((g_row=mysql_fetch_row(g_res))) // 打印结果集
        printf("%s\t%s\n", g_row[0], g_row[1]); // 第一,第二字段

    mysql_free_result(g_res); // 释放结果集

    mysql_close(g_conn); // 关闭链接

    return EXIT_SUCCESS;
}

运行结果:

!!!Hello World!!!

共1个记录,每个记录2字段
id    name

2    testname

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值