c语言和sqlserver的交互
时间: 2023-09-15 16:22:24 浏览: 179
在C语言中,可以使用ODBC(Open Database Connectivity)API来连接SQL Server数据库。ODBC是一种标准的数据库访问接口,可以在多种操作系统和编程语言中使用。
以下是一个简单的示例代码,演示如何使用ODBC连接SQL Server数据库,并执行一个查询:
```
#include <stdio.h>
#include <windows.h>
#include <sql.h>
#include <sqlext.h>
int main() {
SQLHENV henv; // Environment handle
SQLHDBC hdbc; // Connection handle
SQLHSTMT hstmt; // Statement handle
SQLRETURN retcode;
// Allocate the environment handle
retcode = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &henv);
if (retcode != SQL_SUCCESS && retcode != SQL_SUCCESS_WITH_INFO) {
// Handle error
return 1;
}
// Set the ODBC version to use
retcode = SQLSetEnvAttr(henv, SQL_ATTR_ODBC_VERSION, (SQLPOINTER) SQL_OV_ODBC3, SQL_IS_INTEGER);
if (retcode != SQL_SUCCESS && retcode != SQL_SUCCESS_WITH_INFO) {
// Handle error
SQLFreeHandle(SQL_HANDLE_ENV, henv);
return 1;
}
// Allocate the connection handle
retcode = SQLAllocHandle(SQL_HANDLE_DBC, henv, &hdbc);
if (retcode != SQL_SUCCESS && retcode != SQL_SUCCESS_WITH_INFO) {
// Handle error
SQLFreeHandle(SQL_HANDLE_ENV, henv);
return 1;
}
// Connect to the database
retcode = SQLConnect(hdbc, (SQLCHAR*) "MyServer", SQL_NTS, (SQLCHAR*) "MyDatabase", SQL_NTS, (SQLCHAR*) "MyUsername", SQL_NTS, (SQLCHAR*) "MyPassword", SQL_NTS);
if (retcode != SQL_SUCCESS && retcode != SQL_SUCCESS_WITH_INFO) {
// Handle error
SQLFreeHandle(SQL_HANDLE_DBC, hdbc);
SQLFreeHandle(SQL_HANDLE_ENV, henv);
return 1;
}
// Allocate the statement handle
retcode = SQLAllocHandle(SQL_HANDLE_STMT, hdbc, &hstmt);
if (retcode != SQL_SUCCESS && retcode != SQL_SUCCESS_WITH_INFO) {
// Handle error
SQLDisconnect(hdbc);
SQLFreeHandle(SQL_HANDLE_DBC, hdbc);
SQLFreeHandle(SQL_HANDLE_ENV, henv);
return 1;
}
// Execute a query
retcode = SQLExecDirect(hstmt, (SQLCHAR*) "SELECT * FROM MyTable", SQL_NTS);
if (retcode != SQL_SUCCESS && retcode != SQL_SUCCESS_WITH_INFO) {
// Handle error
SQLFreeHandle(SQL_HANDLE_STMT, hstmt);
SQLDisconnect(hdbc);
SQLFreeHandle(SQL_HANDLE_DBC, hdbc);
SQLFreeHandle(SQL_HANDLE_ENV, henv);
return 1;
}
// Fetch the results
while (SQLFetch(hstmt) == SQL_SUCCESS) {
// Process each row of results
}
// Free resources
SQLFreeHandle(SQL_HANDLE_STMT, hstmt);
SQLDisconnect(hdbc);
SQLFreeHandle(SQL_HANDLE_DBC, hdbc);
SQLFreeHandle(SQL_HANDLE_ENV, henv);
return 0;
}
```
在实际使用中,需要根据自己的SQL Server配置和需要执行的查询语句进行相应的修改。
阅读全文