本文共 2002 字,大约阅读时间需要 6 分钟。
使用C语言在MySQL中插入数据 - Linux编程教程
当编写Linux程序时,如何通过C语言与MySQL数据库进行交互,是一个常见且实用的技能。本节重点介绍如何使用mysql
客户端库在C程序中实现数据库插入操作。
首先,确保你已经安装了MySQL数据库服务器和C语言编译环境。完成以下步骤:
在终端中,输入sudo apt-get install mysql-server
来安装MySQL数据库(如果是新安装)。
启动MySQL服务:sudo systemctl start mysql
。
确认数据库是否正常运行:使用mysql
命令登录数据库。
mysql -u root -p
输入root用户的密码。
创建一个数据库:CREATE DATABASE children;
。
使用MySQL提示符执行数据库备用语句:USE children;
。
下面展示了一个完整的C程序示例,用于在children
数据库中插入新记录:
#include#include int main(int argc, char *argv[]) { MYSQL my_connection; int res, status; char *db_name = "children"; char *table_name = "children"; char *insert_query = "INSERT INTO children(fname, age) VALUES('david', 8)"; // 初始化MySQL连接 my_init(&my_connection); // establishing connection if (mysql_real_connect(&my_connection, "localhost", "root", "mysql", db_name, 0, NULL, 0)) { printf("Connection success\n"); // 插入数据 res = mysql_query(&my_connection, insert_query); if (!res) { printf("Inserted %d rows\n", 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, "Error code: %d - %s\n", mysql_errno(&my_connection), mysql_error(&my_connection)); } } return EXIT_SUCCESS;}
在插入数据之前,请确保已经:
children
,并为插入操作准备好数据。完成插入操作后,程序会输出以下信息:
Connection success
Inserted X rows
其中X
是插入的记录数。此外,记得在程序退出之前关闭数据库连接,避免资源泄漏。
通过以上代码示例,你可以轻松地在C语言程序中与MySQL进行交互,并实现数据的插入操作。练习并修改代码以适应不同的数据库和表结构。
转载地址:http://kjwfk.baihongyu.com/