C语言接口使用示例
在计算机编程中,数据库是存储和管理数据的重要工具,C语言是一种通用的、过程式的编程语言,它提供了与数据库进行交互的接口,本文将介绍如何使用C语言接口来操作数据库。
1、数据库连接
在使用C语言接口操作数据库之前,首先需要建立与数据库的连接,这可以通过调用数据库提供的函数或库来完成,下面是一个示例代码,演示了如何连接到一个名为"mydatabase"的数据库:
#include#include int main() { MYSQL *conn; MYSQL_RES *res; MYSQL_ROW row; // 创建数据库连接 conn = mysql_init(NULL); if (conn == NULL) { fprintf(stderr, "Error: %s ", mysql_error(conn)); return 1; } // 连接到数据库 if (mysql_real_connect(conn, "localhost", "username", "password", "mydatabase", 0, NULL, 0) == NULL) { fprintf(stderr, "Error: %s ", mysql_error(conn)); mysql_close(conn); return 1; } // 执行查询语句并获取结果集 if (mysql_query(conn, "SELECT * FROM mytable")) { fprintf(stderr, "Error: %s ", mysql_error(conn)); mysql_close(conn); return 1; } res = mysql_use_result(conn); while ((row = mysql_fetch_row(res)) != NULL) { printf("%s ", row[0]); } // 释放结果集和关闭数据库连接 mysql_free_result(res); mysql_close(conn); return 0; }
上述代码使用了MySQL数据库的C语言接口,通过调用mysql_init
函数初始化了一个数据库连接对象,使用mysql_real_connect
函数连接到指定的数据库,接下来,执行了一个查询语句,并通过mysql_use_result
函数获取了结果集,遍历结果集并打印出每一行的数据,释放结果集和关闭数据库连接。
2、执行查询语句
除了执行简单的查询语句外,C语言接口还支持执行其他类型的SQL语句,如插入、更新和删除等,下面是一个示例代码,演示了如何执行一个插入语句:
#include#include int main() { MYSQL *conn; int affected_rows; // 创建数据库连接并连接到数据库(同上) ... // 执行插入语句并获取受影响的行数 if (mysql_query(conn, "INSERT INTO mytable (column1, column2) VALUES ('value1', 'value2')")) { fprintf(stderr, "Error: %s ", mysql_error(conn)); mysql_close(conn); return 1; } affected_rows = mysql_affected_rows(conn); printf("Inserted %d rows. ", affected_rows); // 释放数据库连接(同上) ... }
上述代码在连接到数据库后,执行了一个插入语句,通过调用mysql_query
函数执行SQL语句,并通过mysql_affected_rows
函数获取受影响的行数,打印出受影响的行数,需要注意的是,插入语句中的列名和值需要根据实际情况进行替换。
上一篇:存储程序工作原理特点_工作原理