C语言输出sql server数据
时间: 2024-05-07 15:18:36 浏览: 140
SQL Server数据库 习题
要输出 SQL Server 数据,可以使用 ODBC API 和 C 语言编写程序连接到 SQL Server 数据库。以下是一个简单的示例程序,可以用来连接到 SQL Server 数据库,并查询并输出数据。
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sql.h>
#include <sqlext.h>
void show_error(unsigned int handletype, const SQLHANDLE& handle, const char* message)
{
SQLCHAR sqlstate[1024];
SQLCHAR message[1024];
if (SQL_SUCCESS == SQLGetDiagRec(handletype, handle, 1, sqlstate, NULL, message, 1024, NULL))
{
printf("%s: %s\n", message, sqlstate);
}
}
int main()
{
SQLHENV env;
SQLHDBC dbc;
SQLHSTMT stmt;
SQLRETURN ret;
SQLCHAR outstr[1024];
SQLSMALLINT outstrlen;
char* conn_str =
"Driver={SQL Server};"
"Server=localhost;"
"Database=your_database_name;"
"UID=your_username;"
"PWD=your_password;";
// Allocate an environment handle
SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &env);
SQLSetEnvAttr(env, SQL_ATTR_ODBC_VERSION, (void*)SQL_OV_ODBC3, 0);
// Allocate a connection handle
SQLAllocHandle(SQL_HANDLE_DBC, env, &dbc);
// Connect to the DSN
ret = SQLDriverConnect(dbc, NULL, (SQLCHAR*)conn_str, SQL_NTS, outstr, sizeof(outstr), &outstrlen, SQL_DRIVER_NOPROMPT);
if (SQL_SUCCESS != ret && SQL_SUCCESS_WITH_INFO != ret)
{
show_error(SQL_HANDLE_DBC, dbc, "SQLDriverConnect failed");
return EXIT_FAILURE;
}
// Allocate a statement handle
SQLAllocHandle(SQL_HANDLE_STMT, dbc, &stmt);
// Execute the query
ret = SQLExecDirect(stmt, (SQLCHAR*)"SELECT * FROM your_table_name", SQL_NTS);
if (SQL_SUCCESS != ret && SQL_SUCCESS_WITH_INFO != ret)
{
show_error(SQL_HANDLE_STMT, stmt, "SQLExecDirect failed");
return EXIT_FAILURE;
}
// Fetch and print the results
SQLCHAR name[1024];
int age;
while (SQLFetch(stmt) == SQL_SUCCESS)
{
SQLGetData(stmt, 1, SQL_C_CHAR, name, sizeof(name), NULL);
SQLGetData(stmt, 2, SQL_C_LONG, &age, sizeof(age), NULL);
printf("%s, %d\n", name, age);
}
// Free the statement handle
SQLFreeHandle(SQL_HANDLE_STMT, stmt);
// Disconnect
SQLDisconnect(dbc);
// Free the connection handle
SQLFreeHandle(SQL_HANDLE_DBC, dbc);
// Free the environment handle
SQLFreeHandle(SQL_HANDLE_ENV, env);
return EXIT_SUCCESS;
}
```
在程序中,需要替换 `your_database_name`、`your_username`、`your_password` 和 `your_table_name` 为实际的数据库名称、用户名、密码和表名。然后编译并运行程序即可输出 SQL Server 数据库中的数据。
阅读全文