腾讯云轻量服务器上CentOS 7.6使用C语言连接MySQL和查询MySQL

我这里已经把MySQL服务器装好了,然后我开始使用sudo yum install mysql-devel安装MySQL开发工具。
腾讯云轻量服务器上CentOS 7.6使用C语言连接MySQL和查询MySQL_第1张图片接下来进行建立数据库、建表和插入数据:

-- 进入到mysql命令行
-- mysql -u root -p
-- 输入密码
-- 建数据库语句,库名是“school”
create database school;
-- 使用school这个数据库
use school;
-- 建表语句,表名是“student”
CREATE TABLE student(
        no int(11) NOT NULL PRIMARY KEY auto_increment,
        name varchar(30),
        age int(11)
       );
-- 插入语句
INSERT INTO student(age,name) VALUES (1,'start');

C语言的文件名为selectstudent.c,进行C语言的编码:

#include 
#include "mysql.h"
#include 
#include 
int main()
{
   MYSQL sql;
   int res;
   MYSQL_RES * result;
   MYSQL_ROW row;
  mysql_init(&sql); //初始化MYSQL结构体
  if (&sql==NULL)
  {
    printf("init error\n");
    return 1;
  }


  if (NULL==mysql_real_connect(&sql,"localhost","root","ILoveYou#3","school",0,NULL,0))//用户为root@localhost , 密码是ILoveYou#3, 数据库是school
  {
    printf("connect error\n");
    printf("error:%d: %s\n",mysql_errno(&sql),mysql_error(&sql));//连接失败打印具体的错误信息
    return 1;
  }
  printf("connect success\n");
  char select_query[] = "select * from student";
  printf("SQL语句为  %s\n", select_query);
  if (mysql_query(&sql, select_query) != 0) {
       fprintf(stderr, "查询失败\n");
       exit(1);
    }else {
           if ((result = mysql_store_result(&sql)) == NULL) {
              fprintf(stderr, "保存结果集失败\n");
               exit(1);
            }else {
                        while ((row = mysql_fetch_row(result)) != NULL) {
                            printf("studentno is %s,",row[0]);
                            printf("name is %s , ", row[1]);
                            printf("age is %s\n", row[2]);
                        }
                    }
               }
  mysql_close(&sql);
  return 0;
}

使用gcc -I/usr/include/mysql -L/usr/lib64/mysql -lmysqlclient selectstudent.c进行编译,然后使用./a.out运行。
编译运行

第一次使用sudo yum install mysql-devel这个命令时,遇到下面的报错:

Downloading packages:
warning: /var/cache/yum/x86_64/7/mysql57-community/packages/mysql-community-deve                                                                                                             l-5.7.37-1.el7.x86_64.rpm: Header V4 RSA/SHA256 Signature, key ID 3a79bd29: NOKE                                                                                                             Y
Retrieving key from file:///etc/pki/rpm-gpg/RPM-GPG-KEY-mysql


The GPG keys listed for the "MySQL 5.7 Community Server" repository are already                                                                                                              installed but they are not correct for this package.
Check that the correct key URLs are configured for this repository.


 Failing package is: mysql-community-devel-5.7.37-1.el7.x86_64
 GPG Keys are configured as: file:///etc/pki/rpm-gpg/RPM-GPG-KEY-mysql

我的解决方法是:rpm --import https://repo.mysql.com/RPM-GPG-KEY-mysql-2022

你可能感兴趣的:(C语言,mysql,腾讯云,c语言)