>  기사  >  php教程  >  C++ 프레임워크 라이브러리 애플리케이션: 데이터베이스 연결 풀

C++ 프레임워크 라이브러리 애플리케이션: 데이터베이스 연결 풀

高洛峰
高洛峰원래의
2016-11-02 14:45:031985검색

Poco C++의 데이터베이스 드라이버 부분은 간단하고 깔끔하며 데이터베이스와 연결되어 있어 비교적 사용하기 쉽습니다.

한 가지 요구 사항 설명

MySQL 데이터베이스와 연결 풀을 설정하고 연결 풀에서 연결을 얻어 데이터베이스에 일반적인 추가, 삭제, 수정 및 쿼리를 구현합니다.

초 목표 설명

ANSI 스타일 코드를 작성하고 높은 수준의 결과를 터미널에 출력하여 프로그램의 유효성을 확인합니다

세 가지 디버깅 조건:

1. 시스템: ubuntu

2.qt 또는 기타 IDE

3. mysql을 설치하고 올바른 액세스 계정과 비밀번호를 갖습니다.

4가지 루틴 지침

IDE 사용: Qt Creator

프로젝트 파일: pocomysql.pro

QT       += core network
QT       -= gui
TARGET = poco_mysql
CONFIG   += console
CONFIG   -= app_bundle
 
DEFINES += CHARTDIR_HIDE_OBSOLETE _CRT_SECURE_NO_WARNINGS
INCLUDEPATH += /usr/local/include/Poco -I /usr/include/mysql
LIBS += -L/usr/local/lib -lPocoData -lPocoDataMySQL -lPocoDataSQLite  -lPocoCrypto   -lPocoUtil -lPocoFoundation -L /usr/lib64/mysql
#LIBS += -L/usr/local/lib -lPocoData  -lPocoDataSQLite   -lPocoFoundation  -lPocoCrypto   -lPocoUtil
SOURCES += \
    mysql.cpp

메인 파일

#include "Poco/String.h"
#include "Poco/Format.h"
#include "Poco/Exception.h"
#include "Poco/Data/StatementImpl.h"
#include "Poco/Data/MySQL/Connector.h"
#include "Poco/Data/MySQL/MySQLException.h"
#include "Poco/Data/Session.h"
#include "Poco/Data/SessionPool.h"
#include "Poco/Data/SessionFactory.h"
#include "Poco/Data/LOB.h"
#include "Poco/Data/MySQL/MySQLStatementImpl.h"
#include "Poco/DateTime.h"
#include "Poco/Data/RecordSet.h"
#include "Poco/Data/Column.h"
 
#include <iostream>
 
using namespace Poco::Data::Keywords;
using namespace Poco::Data;
using Poco::Data::Session;
using Poco::Data::MySQL::ConnectionException;
using Poco::Data::MySQL::StatementException;
using Poco::NotFoundException;
using Poco::Data::Statement;
using Poco::DateTime;
using Poco::Data::RecordSet;
//给出访问数据库的信息
std::string _dbConnString  = "host=localhost;port=3306;"
                                                "user=root;password=19810311;"
                                                "db=smart;"
                                                "compress=true;auto-reconnect=true";
 
int main(int argc, char** argv)
{
        MySQL::Connector::registerConnector();
        //与数据库建立一个连接池
        Poco::Data::SessionPool pool(MySQL::Connector::KEY, _dbConnString,1,32,10);
        //从数据库存连接池中获得一个数据库连接
        Poco::Data::Session ses(pool.get());
        //如果与数据库建立会话成功,输出连接信息
        if(ses.isConnected())
             std::cout << "*** Connected to " << &#39;(&#39; << _dbConnString << &#39;)&#39; << std::endl;
        //如果有为名ddjj的表,先删除,方便下面调试
        ses << "DROP TABLE IF EXISTS ddjj", now;
 
        //把查询结果存储到容器中
        std::vector<std::string> names;
        ses << "show databases",into(names), now;
       //输出查询结果,此处列出所有数据库名称
        for (std::vector<std::string>::const_iterator it = names.begin(); it != names.end(); ++it)
        {
            std::cout << *it << std::endl;
        }
 
        // 建立一个表,名为ddjj,字段名:name,sex
        ses << "create table ddjj(name VARCHAR(20),sex VARCHAR(20));", now;
       //实现数据纪录的插入
        DateTime bd(1980, 4, 1);
        DateTime ld(1982, 5, 9);
        ses << "INSERT INTO ddjj VALUES(&#39;Bart Simpson&#39;,  ?)", use(bd), now;
        ses << "INSERT INTO ddjj VALUES(&#39;Lisa Simpson&#39;,  ?)", use(ld), now;
       //实现查询的方法,并输出查询结果
        std::vector<std::string> names1;
        ses << "select * from ddjj where name like &#39;Bart Simpson&#39; ",
            into(names1),
            now;
        for (std::vector<std::string>::const_iterator it = names1.begin(); it != names1.end(); ++it)
        {
           std::cout << "*** tables: " << *it << std::endl;
        }
 
        Statement select(ses);
        select << "SELECT * FROM ddjj";
        select.execute();
 
        //创建纪录集
        RecordSet rs(select);
        std::size_t cols = rs.columnCount();
        //输出列名
        for (std::size_t col = 0; col < cols; ++col)
        {
            std::cout << rs.columnName(col) << std::endl;
        }
        //输出所有查询到的结果
        bool more = rs.moveFirst();
        while (more)
        {
            for (std::size_t col = 0; col < cols; ++col)
            {
                std::cout << rs[col].convert<std::string>() << " ";
            }
            std::cout << std::endl;
            more = rs.moveNext();
        }
 
        ses.close();
        MySQL::Connector::unregisterConnector();
        return 0;
}

4개의 출력 결과

*** 연결됨(host=localhost) ;port=3306;user=root;password=19810311;db =smart;compress=true;auto-reconnect=true)

information_schema

mysql

performance_schema

스마트

*** 테이블: Bart Simpson

이름

성별

Bart Simpson 1980-04-01 00:00:00

리사 심슨 1982-05-09 00:00:00


성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.