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語(yǔ)言實(shí)現(xiàn)簡(jiǎn)單的三子棋項(xiàng)目
這篇文章主要為大家詳細(xì)介紹了C語(yǔ)言實(shí)現(xiàn)簡(jiǎn)單的三子棋項(xiàng)目,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-08-08
C++實(shí)現(xiàn)一維向量旋轉(zhuǎn)算法
這篇文章主要介紹了C++實(shí)現(xiàn)一維向量旋轉(zhuǎn)算法,非常實(shí)用的經(jīng)典算法,需要的朋友可以參考下2014-08-08
C語(yǔ)言中獲取進(jìn)程識(shí)別碼的相關(guān)函數(shù)
這篇文章主要介紹了C語(yǔ)言中獲取進(jìn)程識(shí)別碼的相關(guān)函數(shù),分別為getpid()函數(shù)和getppid()函數(shù)的使用,需要的朋友可以參考下2015-08-08
C++類的構(gòu)造與析構(gòu)特點(diǎn)及作用詳解
本文章將會(huì)可能會(huì)涉及到匯編的知識(shí),不過(guò)沒(méi)有關(guān)系,我會(huì)講的盡量通俗易懂;另外本篇文章開(kāi)始前,建議了解下什么是函數(shù)重載,這個(gè)概念很簡(jiǎn)單的--有相同的函數(shù)名,但參數(shù)列表不相同的函數(shù),就是函數(shù)重載2022-10-10
C++實(shí)現(xiàn)轉(zhuǎn)置矩陣的循環(huán)
大家好,本篇文章主要講的是C++實(shí)現(xiàn)轉(zhuǎn)置矩陣的循環(huán),感興趣的同學(xué)趕快來(lái)看一看吧,對(duì)你有幫助的話記得收藏一下,方便下次瀏覽2022-01-01
Cocos2d-x中CCEditBox文本輸入框的使用實(shí)例
這篇文章主要介紹了Cocos2d-x中CCEditBox文本輸入框的使用實(shí)例,本文在代碼中用大量注釋講解了CCEditBox的使用方法,需要的朋友可以參考下2014-09-09

