c连接sqlserver数据库代码
时间: 2023-06-22 08:17:26 浏览: 131
c#连接sqlserver数据库的代码和方式.pdf
以下是使用 C 语言连接 SQL Server 数据库的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sql.h>
#include <sqlext.h>
#define SQL_RESULT_LEN 240
#define SQL_RETURN_CODE_LEN 1000
void show_error(unsigned int handletype, const SQLHANDLE& handle) {
SQLCHAR sqlstate[1024];
SQLCHAR message[1024];
if (SQL_SUCCESS == SQLGetDiagRec(handletype, handle, 1, sqlstate, NULL, message, 1024, NULL)) {
printf("%s:%s\n", sqlstate, message);
}
}
int main() {
SQLHANDLE sqlenvhandle;
SQLHANDLE sqlconnectionhandle;
SQLHANDLE sqlstatementhandle;
SQLRETURN retcode;
SQLCHAR retconstring[1024];
SQLCHAR* query = (SQLCHAR*)"SELECT * FROM mytable";
SQLCHAR name[SQL_RESULT_LEN];
SQLCHAR address[SQL_RESULT_LEN];
SQLCHAR city[SQL_RESULT_LEN];
SQLINTEGER id;
int i = 0;
if (SQL_SUCCESS != SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &sqlenvhandle))
goto COMPLETED;
if (SQL_SUCCESS != SQLSetEnvAttr(sqlenvhandle, SQL_ATTR_ODBC_VERSION, (SQLPOINTER)SQL_OV_ODBC3, 0))
goto COMPLETED;
if (SQL_SUCCESS != SQLAllocHandle(SQL_HANDLE_DBC, sqlenvhandle, &sqlconnectionhandle))
goto COMPLETED;
retcode = SQLDriverConnect(sqlconnectionhandle, NULL, (unsigned char*)"DRIVER={SQL Server};SERVER=localhost,1433;DATABASE=mydatabase;UID=myusername;PWD=mypassword;", SQL_NTS, retconstring, 1024, NULL, SQL_DRIVER_NOPROMPT);
if (retcode == SQL_SUCCESS || retcode == SQL_SUCCESS_WITH_INFO) {
printf("Connected\n");
}
else {
show_error(SQL_HANDLE_DBC, sqlconnectionhandle);
goto COMPLETED;
}
if (SQL_SUCCESS != SQLAllocHandle(SQL_HANDLE_STMT, sqlconnectionhandle, &sqlstatementhandle))
goto COMPLETED;
if (SQL_SUCCESS != SQLExecDirect(sqlstatementhandle, query, SQL_NTS)) {
show_error(SQL_HANDLE_STMT, sqlstatementhandle);
goto COMPLETED;
}
else {
while (SQLFetch(sqlstatementhandle) == SQL_SUCCESS) {
SQLGetData(sqlstatementhandle, 1, SQL_C_ULONG, &id, 0, NULL);
SQLGetData(sqlstatementhandle, 2, SQL_C_CHAR, name, SQL_RESULT_LEN, NULL);
SQLGetData(sqlstatementhandle, 3, SQL_C_CHAR, address, SQL_RESULT_LEN, NULL);
SQLGetData(sqlstatementhandle, 4, SQL_C_CHAR, city, SQL_RESULT_LEN, NULL);
printf("%d, %s, %s, %s\n", id, name, address, city);
}
}
COMPLETED:
SQLFreeHandle(SQL_HANDLE_STMT, sqlstatementhandle);
SQLDisconnect(sqlconnectionhandle);
SQLFreeHandle(SQL_HANDLE_DBC, sqlconnectionhandle);
SQLFreeHandle(SQL_HANDLE_ENV, sqlenvhandle);
getchar();
return 0;
}
```
你需要在编译前确保已经正确安装了 SQL Server 的 ODBC 驱动程序,并将代码中的服务器、数据库、用户名和密码替换成你自己的。如果有任何问题,请参考 SQL Server 的官方文档或联系 SQL Server 的支持团队。
阅读全文