C++ 写法sqlserver 检查数据是否存
时间: 2023-10-06 11:04:43 浏览: 171
可以使用以下代码片段来检查 SQL Server 数据库中是否存在指定数据:
```c++
#include <iostream>
#include <windows.h>
#include <sqltypes.h>
#include <sql.h>
#include <sqlext.h>
using namespace std;
int main() {
SQLHENV henv; // Environment handle
SQLHDBC hdbc; // Connection handle
SQLHSTMT hstmt; // Statement handle
SQLRETURN retcode; // Return code
// Allocate an environment handle
retcode = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &henv);
// Set the ODBC version environment attribute to 3 (ODBC 3.0)
retcode = SQLSetEnvAttr(henv, SQL_ATTR_ODBC_VERSION, (SQLPOINTER)SQL_OV_ODBC3, SQL_IS_INTEGER);
// Allocate a connection handle
retcode = SQLAllocHandle(SQL_HANDLE_DBC, henv, &hdbc);
// Connect to the database
SQLCHAR* dsn = (SQLCHAR*)"your_dsn_name"; // Data source name
SQLCHAR* user = (SQLCHAR*)"your_username"; // User name
SQLCHAR* pass = (SQLCHAR*)"your_password"; // Password
retcode = SQLConnect(hdbc, dsn, SQL_NTS, user, SQL_NTS, pass, SQL_NTS);
// Allocate a statement handle
retcode = SQLAllocHandle(SQL_HANDLE_STMT, hdbc, &hstmt);
// Execute the query to check if data exists
SQLCHAR* query = (SQLCHAR*)"SELECT COUNT(*) FROM your_table_name WHERE your_condition";
retcode = SQLExecDirect(hstmt, query, SQL_NTS);
// Fetch the result
SQLLEN count;
retcode = SQLFetch(hstmt);
if (retcode == SQL_SUCCESS || retcode == SQL_SUCCESS_WITH_INFO) {
SQLGetData(hstmt, 1, SQL_C_LONG, &count, 0, NULL);
}
// Check if the count is greater than zero
if (count > 0) {
cout << "Data exists!" << endl;
} else {
cout << "Data does not exist!" << endl;
}
// Free the statement handle
retcode = SQLFreeHandle(SQL_HANDLE_STMT, hstmt);
// Disconnect from the database
retcode = SQLDisconnect(hdbc);
// Free the connection handle
retcode = SQLFreeHandle(SQL_HANDLE_DBC, hdbc);
// Free the environment handle
retcode = SQLFreeHandle(SQL_HANDLE_ENV, henv);
return 0;
}
```
在以上代码中,你需要将 `your_dsn_name`、`your_username`、`your_password`、`your_table_name` 和 `your_condition` 替换为你的实际值。如果查询到的结果大于零,说明数据存在于数据库中,否则数据不存在。
阅读全文