C++連接數(shù)據(jù)庫(kù)SqlServer、MySql、Oracle、Access、SQLite、PostgreSQL、MongoDB、Redis
C++是一種通用的編程語(yǔ)言,可以使用不同的庫(kù)和驅(qū)動(dòng)程序來(lái)連接各種數(shù)據(jù)庫(kù)。以下是一些示例代碼,演示如何使用 C++ 連接 SQL Server、MySQL、Oracle、ACCESS、SQLite 、 PostgreSQL、MongoDB、Redis數(shù)據(jù)庫(kù)。
連接 SQL Server 數(shù)據(jù)庫(kù)
要使用 C++ 連接 SQL Server 數(shù)據(jù)庫(kù),可以使用 Microsoft 的 ADODB 庫(kù)。以下是一個(gè)示例代碼:
#include <iostream> #import "C:\Program Files\Common Files\System\ado\msado15.dll" no_namespace rename("EOF", "EndOfFile") int main() { CoInitialize(NULL); // 初始化 COM 庫(kù) _ConnectionPtr pConnection("ADODB.Connection"); // 創(chuàng)建 Connection 對(duì)象 _bstr_t strConnect = "Provider=SQLOLEDB;Data Source=localhost;Initial Catalog=MyDatabase;User ID=sa;Password=123456"; // 連接字符串 pConnection->Open(strConnect, NULL, NULL, NULL); // 連接數(shù)據(jù)庫(kù) if (pConnection->State) { _CommandPtr pCommand("ADODB.Command"); // 創(chuàng)建 Command 對(duì)象 _bstr_t strSQL = "SELECT * FROM MyTable"; // SQL 查詢語(yǔ)句 pCommand->ActiveConnection = pConnection; // 設(shè)置連接對(duì)象 pCommand->CommandText = strSQL; // 設(shè)置 SQL 語(yǔ)句 _RecordsetPtr pRecordset("ADODB.Recordset"); // 創(chuàng)建 Recordset 對(duì)象 pRecordset->Open(pCommand.GetInterfacePtr(), _variant_t((IDispatch *) pConnection, true), adOpenUnspecified, adLockUnspecified, -1); // 執(zhí)行查詢并返回結(jié)果集 while (!pRecordset->EndOfFile) { // 遍歷結(jié)果集 // 處理數(shù)據(jù) } } pConnection->Close(); // 關(guān)閉連接 CoUninitialize(); // 關(guān)閉 COM 庫(kù) return 0; }
連接 MySQL 數(shù)據(jù)庫(kù)
要使用 C++ 連接 MySQL 數(shù)據(jù)庫(kù),可以使用 MySQL Connector/C++ 庫(kù)。以下是一個(gè)示例代碼:
#include <mysql_driver.h> #include <mysql_connection.h> #include <cppconn/driver.h> #include <cppconn/exception.h> #include <cppconn/resultset.h> #include <cppconn/statement.h> int main() { sql::mysql::MySQL_Driver *driver; sql::Connection *con; sql::Statement *stmt; sql::ResultSet *res; driver = sql::mysql::get_mysql_driver_instance(); // 獲取 MySQL 驅(qū)動(dòng)程序?qū)嵗? con = driver->connect("tcp://localhost:3306", "user", "password"); // 連接數(shù)據(jù)庫(kù) stmt = con->createStatement(); // 創(chuàng)建 Statement 對(duì)象 res = stmt->executeQuery("SELECT * FROM MyTable"); // 執(zhí)行查詢并返回結(jié)果集 while (res->next()) { // 遍歷結(jié)果集 // 處理數(shù)據(jù) } delete res; // 刪除結(jié)果集對(duì)象 delete stmt; // 刪除 Statement 對(duì)象 delete con; // 刪除連接對(duì)象 return 0; }
連接 Oracle 數(shù)據(jù)庫(kù)
要使用 C++ 連接 Oracle 數(shù)據(jù)庫(kù),可以使用 Oracle 提供的 ODBC 驅(qū)動(dòng)程序。以下是一個(gè)示例代碼:
#include <iostream> #include <windows.h> #include <occi.h> using namespace oracle::occi; int main() { Environment *env = Environment::createEnvironment(); // 創(chuàng)建 OCCI 環(huán)境 Connection *conn = env->createConnection("DRIVER={Oracle ODBC Driver};SERVER=localhost;DATABASE=MyDatabase;UID=user;PWD=password"); // 連接數(shù)據(jù)庫(kù) if (conn->isValid()) { Statement *stmt = conn->createStatement("SELECT * FROM MyTable"); // 創(chuàng)建 Statement 對(duì)象 ResultSet *res = stmt->executeQuery(); // 執(zhí)行查詢并返回結(jié)果集 while (res->next()) { // 遍歷結(jié)果集 // 處理數(shù)據(jù) } } conn->close(); // 關(guān)閉連接 env->terminate(); // 關(guān)閉 OCCI 環(huán)境 return 0; }
連接 Access 數(shù)據(jù)庫(kù)
要使用 C++ 連接 Access 數(shù)據(jù)庫(kù),可以使用 Microsoft 的 ADODB 庫(kù)。以下是一個(gè)示例代碼:
#include <iostream> #import "C:\Program Files\Common Files\System\ado\msado15.dll" no_namespace rename("EOF", "EndOfFile") int main() { CoInitialize(NULL); // 初始化 COM 庫(kù) _ConnectionPtr pConnection("ADODB.Connection"); // 創(chuàng)建 Connection 對(duì)象 _bstr_t strConnect = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\MyDatabase.mdb;Persist Security Info=False"; // 連接字符串 pConnection->Open(strConnect, "", "", adConnectUnspecified); // 連接數(shù)據(jù)庫(kù) if (pConnection->State) { _CommandPtr pCommand("ADODB.Command"); // 創(chuàng)建 Command 對(duì)象 _bstr_t strSQL = "SELECT * FROM MyTable"; // SQL 查詢語(yǔ)句 pCommand->ActiveConnection = pConnection; // 設(shè)置連接對(duì)象 pCommand->CommandText = strSQL; // 設(shè)置 SQL 語(yǔ)句 _RecordsetPtr pRecordset("ADODB.Recordset"); // 創(chuàng)建 Recordset 對(duì)象 pRecordset->Open(pCommand.GetInterfacePtr(), _variant_t((IDispatch *) pConnection, true), adOpenUnspecified, adLockUnspecified, -1); // 執(zhí)行查詢并返回結(jié)果集 while (!pRecordset->EndOfFile) { // 遍歷結(jié)果集 // 處理數(shù)據(jù) } } pConnection->Close(); // 關(guān)閉連接 CoUninitialize(); // 關(guān)閉 COM 庫(kù) return 0; }
連接 SQLite 數(shù)據(jù)庫(kù)
要使用 C++ 連接 SQLite 數(shù)據(jù)庫(kù),可以使用SQLite C++庫(kù)。以下是一個(gè)示例代碼:
#include <iostream> #include <sqlite3.h> #include <cassert> int main() { sqlite3* db; int rc; std::string sql; // 打開(kāi)數(shù)據(jù)庫(kù) rc = sqlite3_open("MyDatabase.db", &db); assert(rc == SQLITE_OK); // 創(chuàng)建表格 sql = "CREATE TABLE IF NOT EXISTS MyTable(id INTEGER PRIMARY KEY, name TEXT);"; rc = sqlite3_exec(db, sql.c_str(), NULL, NULL, NULL); assert(rc == SQLITE_OK); // 插入數(shù)據(jù) sql = "INSERT INTO MyTable(name) VALUES('hello');"; rc = sqlite3_exec(db, sql.c_str(), NULL, NULL, NULL); assert(rc == SQLITE_OK); // 查詢數(shù)據(jù) sql = "SELECT * FROM MyTable;"; rc = sqlite3_exec(db, sql.c_str(), callback, 0, 0); assert(rc == SQLITE_OK); // 關(guān)閉數(shù)據(jù)庫(kù) sqlite3_close(db); return 0; }
連接 PostgreSQL 數(shù)據(jù)庫(kù)
要使用 C++ 連接 PostgreSQL 數(shù)據(jù)庫(kù),可以使用 PostgreSQL C++ 驅(qū)動(dòng)程序。以下是一個(gè)示例代碼:
#include <iostream> #include <postgresql/libpq-fe.h> #include <cassert> void callback(void* arg, int argc, char** argv, char** cols) { for (int i = 0; i < argc; i++) { std::cout << cols[i] << ": " << argv[i] << std::endl; } } int main() { PGconn* conn = PQconnectdb("host=localhost dbname=MyDatabase user=user password=password"); assert(PQstatus(conn) == CONNECTION_OK); // 執(zhí)行查詢 PGresult* res = PQexec(conn, "SELECT * FROM MyTable"); assert(PQresultStatus(res) == PGRES_TUPLES_OK); // 遍歷結(jié)果集 for (int i = 0; i < PQntuples(res); i++) { callback(NULL, PQnfields(res), PQgetvalue(res, i), PQgetisnull(res, i)); } // 關(guān)閉連接 PQfinish(conn); return 0; }
連接MongoDB數(shù)據(jù)庫(kù)
#include <iostream> #include <mongocxx/client.hpp> #include <mongocxx/instance.hpp> #include <bsoncxx/json.hpp> #include <bsoncxx/types.hpp> int main() { mongocxx::instance instance{}; mongocxx::client conn{mongocxx::uri{"mongodb://localhost:27017"}}; // 連接到數(shù)據(jù)庫(kù) mongocxx::database db = conn["MyDatabase"]; // 創(chuàng)建文檔 bsoncxx::builder::stream::document doc{}; doc << "name" << "John Doe" << "age" << 30 << "email" << "johndoe@example.com"; // 插入文檔到集合 db["MyCollection"].insert(doc.view()); // 查詢文檔 mongocxx::cursor cursor = db["MyCollection"].find({}); while (cursor) { bsoncxx::document::view doc = cursor->view(); std::cout << doc["name"].get_string() << std::endl; std::cout << doc["age"].get_int32() << std::endl; std::cout << doc["email"].get_string() << std::endl; cursor++; } return 0; }
這個(gè)示例使用了MongoDB C++驅(qū)動(dòng)程序來(lái)連接到MongoDB數(shù)據(jù)庫(kù),創(chuàng)建文檔并將其插入到集合中,然后查詢并打印文檔的內(nèi)容。
連接Redis數(shù)據(jù)庫(kù)
#include "stdafx.h" #include <Windows.h> #include <hiredis.h> #pragma comment(lib, "Win32_Interop.lib") #pragma comment(lib, "hiredis.lib") int main() { //redis默認(rèn)監(jiān)聽(tīng)端口為6387 可以再配置文件中修改 redisContext* pRedisContext = redisConnect("127.0.0.1", 6379); if (NULL == pRedisContext || pRedisContext->err) { printf("%s \r\n", pRedisContext->errstr); printf("Connect to redis server failed \n"); return -1; } //輸入Redis密碼 const char *pszRedisPwd = "123456"; redisReply *pRedisReply = (redisReply*)redisCommand(pRedisContext, "AUTH %s", pszRedisPwd); if (NULL != pRedisReply) { freeReplyObject(pRedisReply); } //用get命令獲取數(shù)據(jù) char szRedisBuff[256] = { 0 }; sprintf_s(szRedisBuff, "GET %s", "name"); pRedisReply = (redisReply*)redisCommand(pRedisContext, szRedisBuff); if (NULL == pRedisReply) { printf("Get data Error!"); return -1; } if (NULL == pRedisReply->str) { freeReplyObject(pRedisReply); return -1; } string strRes(pRedisReply->str); freeReplyObject(pRedisReply); //向Redis寫入數(shù)據(jù) pRedisReply = (redisReply *)redisCommand(pRedisContext, "SET keyName huantest"); if (NULL != pRedisReply) { freeReplyObject(pRedisReply); } return 0; }
總結(jié)
到此這篇關(guān)于C++連接數(shù)據(jù)庫(kù)SqlServer、MySql、Oracle、Access、SQLite、PostgreSQL、MongoDB、Redis的文章就介紹到這了,更多相關(guān)C++連接8種數(shù)據(jù)庫(kù)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C++指針和數(shù)組:字符和字符串、字符數(shù)組的關(guān)聯(lián)和區(qū)別
字符串是一種重要的數(shù)據(jù)類型,但是c語(yǔ)言并沒(méi)有顯示的字符串?dāng)?shù)據(jù)類型,因?yàn)樽址宰址A康男问匠霈F(xiàn)或者存儲(chǔ)于字符數(shù)組中。在C++標(biāo)準(zhǔn)模板庫(kù)(STL)中提供了string類,實(shí)現(xiàn)了對(duì)字符串的封裝。2022-12-12C語(yǔ)言實(shí)現(xiàn)簡(jiǎn)易三子棋游戲
這篇文章主要為大家詳細(xì)介紹了C語(yǔ)言實(shí)現(xiàn)簡(jiǎn)易三子棋游戲,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-04-04C++實(shí)現(xiàn)文件逐行讀取與字符匹配的示例詳解
這篇文章主要為大家詳細(xì)介紹了如何溧陽(yáng)C++實(shí)現(xiàn)文件逐行讀取與字符匹配的功能,文中的示例代碼講解詳細(xì),具有一定的借鑒價(jià)值,需要的可以參考一下2023-03-03C++制作鼠標(biāo)連點(diǎn)器實(shí)例代碼
大家好,本篇文章主要講的是C++制作鼠標(biāo)連點(diǎn)器實(shí)例代碼,感興趣的同學(xué)趕快來(lái)看一看吧,對(duì)你有幫助的話記得收藏一下,方便下次瀏覽2022-01-01C++實(shí)現(xiàn)LeetCode(113.二叉樹(shù)路徑之和之二)
這篇文章主要介紹了C++實(shí)現(xiàn)LeetCode(113.二叉樹(shù)路徑之和之二),本篇文章通過(guò)簡(jiǎn)要的案例,講解了該項(xiàng)技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下2021-07-07