gpt4 book ai didi

c++ - 如何通过C++连接到我的SQL数据库?

转载 作者:行者123 更新时间:2023-12-02 10:30:59 26 4
gpt4 key购买 nike

我已经看到了一些类似的问题,但是大多数问题都基于PHP,有一个问题基于C,但是唯一的答案是我已经完成的 SQLConnect()文档。
https://docs.microsoft.com/en-us/sql/odbc/reference/syntax/sqlconnect-function?redirectedfrom=MSDN&view=sql-server-ver15

似乎在线上内容很少,我也是一个初学者,所以请原谅任何愚蠢的问题。
我使用MYSQL Workbench设置了SQL数据库,它位于我的localhost:3306上。我能够将其成功连接到ODBC数据源管理程序。

因此,我相信我使用的是正确的函数,并且设置了正确的SQL后端,我只是不知道从这里开始。

最终目标是能够使用该程序将记录“插入”到我的数据库中,也可以从中“选择”。

我在做什么错了,或者我想念什么?

    # include <stdio.h>
# include <stdlib.h>
# include <sql.h>
# include <sqlext.h>
# include <cstdio>
# include <cstdint>
using namespace std;

int main(){
SQLHENV henv = NULL;
SQLHDBC hdbc = NULL;

/* Initialize the ODBC environment handle. */
SQLAllocHandle(SQL_HANDLE_ENV, NULL, &henv);

/* Set the ODBC version to version 3 (the highest version) */
SQLSetEnvAttr(henv, SQL_ATTR_ODBC_VERSION,
(void*)SQL_OV_ODBC3, 0);

/* Allocate the connection handle. */
SQLAllocHandle(SQL_HANDLE_DBC, henv, &hdbc);

SQLConnectW(hdbc, (SQLWCHAR*)"localhost", (SQLSMALLINT) 9,
(SQLWCHAR*)"root", (SQLSMALLINT)4,
(SQLWCHAR*)"password", (SQLSMALLINT)8);

return(0);
}

最佳答案

我在代码中添加了注释,这将帮助您轻松理解代码。
积分:Link

/* Includes Standard C++  */

#include <stdlib.h>
#include <iostream>

/*
Include directly the different
headers from cppconn/ and mysql_driver.h + mysql_util.h
(and mysql_connection.h). This will reduce your build time!
*/

#include "mysql_connection.h"
#include <cppconn/driver.h>
#include <cppconn/exception.h>
#include <cppconn/resultset.h>
#include <cppconn/statement.h>

using namespace std;

int main(void)
{
cout << endl;
cout << "Running 'SELECT 'Successfull' »
AS _message'..." << endl;

try {
sql::Driver *driver;
sql::Connection *con;
sql::Statement *stmt;
sql::ResultSet *res;

/* Create a connection */
driver = get_driver_instance();
con = driver->connect("tcp://127.0.0.1:3306", "root", "root");
/* Connect to the MySQL test database */
con->setSchema("test");

stmt = con->createStatement();
res = stmt->executeQuery("SELECT 'Successfull' AS _message"); // replace with your statement
while (res->next()) {
cout << "\t... MySQL replies: ";
/* Access column data by alias or column name */
cout << res->getString("_message") << endl;
cout << "\t... MySQL says it again: ";
/* Access column fata by numeric offset, 1 is the first column */
cout << res->getString(1) << endl;
}
delete res;
delete stmt;
delete con;

} catch (sql::SQLException &e) {
cout << "# ERR: SQLException in " << __FILE__;
cout << "(" << __FUNCTION__ << ") on line " »
<< __LINE__ << endl;
cout << "# ERR: " << e.what();
cout << " (MySQL error code: " << e.getErrorCode();
cout << ", SQLState: " << e.getSQLState() << " )" << endl;
}

cout << endl;

return EXIT_SUCCESS;
}

关于c++ - 如何通过C++连接到我的SQL数据库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62292910/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com