linux下c语言读取mssql中数据的代码并且保证无中文乱码
时间: 2024-03-03 18:46:51 浏览: 184
要在Linux下使用C语言读取MSSQL中的数据,需要使用ODBC API接口。以下是一个简单的示例代码,可以读取MSSQL数据库中的数据,并保证无中文乱码。
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sql.h>
#include <sqlext.h>
#define SQL_RESULT_LEN 1024
#define SQL_RETURN_CODE_LEN 1000
int main() {
SQLHENV env;
SQLHDBC dbc;
SQLHSTMT stmt;
SQLRETURN ret;
SQLCHAR *dsn = (SQLCHAR *)"your_dsn_name";
SQLCHAR *user = (SQLCHAR *)"your_username";
SQLCHAR *pass = (SQLCHAR *)"your_password";
SQLCHAR sql[SQL_RESULT_LEN];
SQLCHAR name[SQL_RESULT_LEN];
SQLCHAR age[SQL_RESULT_LEN];
SQLCHAR address[SQL_RESULT_LEN];
SQLCHAR phone[SQL_RESULT_LEN];
SQLCHAR return_code[SQL_RETURN_CODE_LEN];
SQLINTEGER ptr_sql;
ret = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &env);
if (ret != SQL_SUCCESS && ret != SQL_SUCCESS_WITH_INFO) {
printf("Error allocating SQL environment handle.\n");
return 1;
}
ret = SQLSetEnvAttr(env, SQL_ATTR_ODBC_VERSION, (void *)SQL_OV_ODBC3, 0);
if (ret != SQL_SUCCESS && ret != SQL_SUCCESS_WITH_INFO) {
printf("Error setting SQL environment attribute.\n");
return 1;
}
ret = SQLAllocHandle(SQL_HANDLE_DBC, env, &dbc);
if (ret != SQL_SUCCESS && ret != SQL_SUCCESS_WITH_INFO) {
printf("Error allocating SQL connection handle.\n");
return 1;
}
ret = SQLConnect(dbc, dsn, SQL_NTS, user, SQL_NTS, pass, SQL_NTS);
if (ret != SQL_SUCCESS && ret != SQL_SUCCESS_WITH_INFO) {
printf("Error connecting to the database.\n");
return 1;
}
ret = SQLAllocHandle(SQL_HANDLE_STMT, dbc, &stmt);
if (ret != SQL_SUCCESS && ret != SQL_SUCCESS_WITH_INFO) {
printf("Error allocating SQL statement handle.\n");
return 1;
}
// 注意:这里的 SQL 语句需要根据实际情况进行修改
ret = SQLExecDirect(stmt, (SQLCHAR *)"SELECT name, age, address, phone FROM your_table_name", SQL_NTS);
if (ret != SQL_SUCCESS && ret != SQL_SUCCESS_WITH_INFO) {
printf("Error executing SQL statement.\n");
return 1;
}
ret = SQLBindCol(stmt, 1, SQL_C_CHAR, name, SQL_RESULT_LEN, &ptr_sql);
ret = SQLBindCol(stmt, 2, SQL_C_CHAR, age, SQL_RESULT_LEN, &ptr_sql);
ret = SQLBindCol(stmt, 3, SQL_C_CHAR, address, SQL_RESULT_LEN, &ptr_sql);
ret = SQLBindCol(stmt, 4, SQL_C_CHAR, phone, SQL_RESULT_LEN, &ptr_sql);
while (SQLFetch(stmt) == SQL_SUCCESS) {
printf("%s\t%s\t%s\t%s\n", name, age, address, phone);
}
SQLFreeHandle(SQL_HANDLE_STMT, stmt);
SQLDisconnect(dbc);
SQLFreeHandle(SQL_HANDLE_DBC, dbc);
SQLFreeHandle(SQL_HANDLE_ENV, env);
return 0;
}
```
为了保证无中文乱码,需要在连接数据库时设置字符集为UTF-8。具体方法是在连接字符串中添加`charset=utf8`,例如:
```c
SQLCHAR *dsn = (SQLCHAR *)"your_dsn_name; charset=utf8";
```
阅读全文