C语言是一种通用的、面向过程的计算机程序设计语言,广泛应用于底层系统开发。SQL Server是由微软开发的关系型数据库管理系统(RDBMS),它提供了强大的数据存储和处理能力。
连接SQL Server数据库的方式主要有以下几种:
C语言连接SQL Server数据库的应用场景包括但不限于:
以下是一个使用ODBC连接SQL Server数据库的简单示例:
#include <stdio.h>
#include <windows.h>
#include <sql.h>
#include <sqlext.h>
void checkSqlError(SQLRETURN ret, SQLSMALLINT handleType, SQLHANDLE handle, const char* msg) {
if (ret != SQL_SUCCESS) {
SQLCHAR sqlState[6], sqlMessage[SQL_MAX_MESSAGE_LENGTH];
SQLSMALLINT i;
SQLINTEGER nativeError;
SQLSMALLINT textLength;
SQLGetDiagRec(handleType, handle, 1, sqlState, &nativeError, sqlMessage, sizeof(sqlMessage), &textLength);
fprintf(stderr, "%s: SQLSTATE=%s, NativeError=%d, Message=%s\n", msg, sqlState, nativeError, sqlMessage);
}
}
int main() {
SQLHENV env;
SQLHDBC dbc;
SQLHSTMT stmt;
SQLRETURN ret;
// Allocate environment handle
ret = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &env);
checkSqlError(ret, SQL_HANDLE_ENV, env, "Failed to allocate environment handle");
// Set the ODBC version environment attribute
ret = SQLSetEnvAttr(env, SQL_ATTR_ODBC_VERSION, (void*)SQL_OV_ODBC3, 0);
checkSqlError(ret, SQL_HANDLE_ENV, env, "Failed to set ODBC version");
// Allocate connection handle
ret = SQLAllocHandle(SQL_HANDLE_DBC, env, &dbc);
checkSqlError(ret, SQL_HANDLE_DBC, dbc, "Failed to allocate connection handle");
// Connect to the database
ret = SQLConnect(dbc, (SQLCHAR*)"YourServerName", SQL_NTS, (SQLCHAR*)"YourUsername", SQL_NTS, (SQLCHAR*)"YourPassword", SQL_NTS);
checkSqlError(ret, SQL_HANDLE_DBC, dbc, "Failed to connect to the database");
if (ret == SQL_SUCCESS) {
printf("Connected to the database successfully!\n");
// Allocate statement handle
ret = SQLAllocHandle(SQL_HANDLE_STMT, dbc, &stmt);
checkSqlError(ret, SQL_HANDLE_STMT, stmt, "Failed to allocate statement handle");
// Execute a query
ret = SQLExecDirect(stmt, (SQLCHAR*)"SELECT * FROM YourTableName", SQL_NTS);
checkSqlError(ret, SQL_HANDLE_STMT, stmt, "Failed to execute query");
if (ret == SQL_SUCCESS) {
SQLCHAR columnValue[256];
while (SQLFetch(stmt) == SQL_SUCCESS) {
SQLGetData(stmt, 1, SQL_C_CHAR, columnValue, sizeof(columnValue), NULL);
printf("Column Value: %s\n", columnValue);
}
}
// Free statement handle
SQLFreeHandle(SQL_HANDLE_STMT, stmt);
}
// Disconnect and free connection handle
SQLDisconnect(dbc);
SQLFreeHandle(SQL_HANDLE_DBC, dbc);
// Free environment handle
SQLFreeHandle(SQL_HANDLE_ENV, env);
return 0;
}
通过以上步骤和示例代码,你应该能够成功连接C语言和SQL Server数据库,并解决常见的连接问题。
领取专属 10元无门槛券
手把手带您无忧上云