下面是一个使用 C 语言连接到 SQL Server 数据库并进行增删改查的示例代码:
#include <stdio.h> #include <stdlib.h> #include <sql.h> #include <sqlext.h>
int main() { // 连接到数据库 SQLHENV env; SQLHDBC dbc; SQLHSTMT stmt; SQLRETURN ret;
// 初始化 ODBC ret = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &env); ret = SQLSetEnvAttr(env, SQL_ATTR_ODBC_VERSION, (void *)SQL_OV_ODBC3, 0); ret = SQLAllocHandle(SQL_HANDLE_DBC, env, &dbc);
// 连接到数据库服务器 SQLCHAR outstr[1024]; SQLSMALLINT outstrlen; ret = SQLDriverConnect(dbc, NULL, "Driver={SQL Server};Server=localhost;Database=test;UID=username;PWD=password", SQL_NTS, outstr, sizeof(outstr), &outstrlen, SQL_DRIVER_NOPROMPT);
if (SQL_SUCCEEDED(ret)) { printf("Connected to the database\n");
// 创建 SQL 语句
char *query = "SELECT * FROM table";
// 分配语句句柄
ret = SQLAllocHandle(SQL_HANDLE_STMT, dbc, &stmt);
// 执行查询
ret = SQLExecDirect(stmt, query, SQL_NTS);
if (SQL_SUCCEEDED(ret)) {
// 处理查询结果
while (SQL_SUCCEEDED(ret = SQLFetch(stmt))) {
// 获取列数
SQLSMALLINT columns;
ret = SQLNumResultCols(stmt, &columns);
// 获取每一列的值
for (int i = 1; i <= columns; i++) {
// 获取列的信息
SQLCHAR column_name[256];
SQLSMALLINT name_len;
SQLSMALLINT data_type;
SQLULEN column_size;
SQLSMALLINT decimal_digits;
SQLSMALLINT nullable;
ret = SQLDescribeCol(stmt, i, column_name, sizeof(column_name), &name_len, &data_type, &column_size, &decimal_digits, &nullable);
// 根据列