续--connection.cpp

本文介绍了一个C++类,用于管理MySQL数据库连接。该类提供了连接、断开连接、查询执行等功能,并能获取数据库版本信息。
#include "connection.hpp"
#include <boost/lexical_cast.hpp>

using namespace sqlpp;

Connection::Connection():_is_open(false),_num_fields(0),_ptr_result(NULL)
{
}

Connection::Connection(const std::string& database, const std::string& server, const std::string& user, const std::string& password):_is_open(false),_num_fields(0),_ptr_result(NULL)
{
  try
    {
      connect(database,server,user,password);
    }
  catch(...)
    {
      throw;
    }
}

Connection::Connection(const char* database, const char* server, const char* user, const char* password):_is_open(false),_num_fields(0),_ptr_result(NULL)
{
  try
    {
      connect(database,server,user,password);
    }
  catch(...)
    {
      throw;
    }
}

Connection::~Connection()
{
  close();
  mysql_library_end();//finially library
}

void Connection::connect()throw(sqlerror)
{
  if ( mysql_init(&_mysql) == NULL)//mysql_library_init invoke by mysql_init because of single-thread mode
  {
    throw sqlerror("mysql_init","return null error");
  }

  //error occur
  if (!mysql_real_connect(&_mysql,_server.c_str(),_user.c_str(),_password.c_str(),_database.c_str(),0,NULL,0))
  {
    try
      {
    check_exception();
      }
    catch(...)
      {
    throw;
      }
  }
  else
  {
    _is_open = true;
  } 
}

void Connection::connect(const std::string& database,
             const std::string& server,
             const std::string& user,
             const std::string& password)throw(sqlerror)
{
  try
    {
      _database = database;
      _server   = server;
      _user     = user;
      _password = password;
      connect();
    }
  catch(...)
    {
      throw;
    }
}

void Connection::connect(const char* database, const char* server, const char* user, const char* password)throw(sqlerror)
{
  try
    {
      _database = database;
      _server   = server;
      _user     = user;
      _password = password;
      connect();
    }
  catch(...)
    {
      throw;
    }
}

bool Connection:: is_open(void)throw()
{
  return _is_open;
}

void Connection::close(void)throw()
{
  if (_is_open)
  {
    mysql_close(&_mysql);
  }
}

std::string Connection::get_client_info(void) throw(sqlerror)
{
  if (!_is_open)
  {
    try
      {
    connect();
      }
    catch(...)
      {
    throw;
      }
  }
  return std::string( mysql_get_client_info() ); 
}

unsigned long Connection::get_client_version(void) throw(sqlerror)
{
  if (!_is_open)
  {
    try
      {
    connect();
      }
    catch(...)
      {
    throw;
      }    
  }
  return  mysql_get_client_version();
}

std::string Connection::get_host_info(void) throw(sqlerror)
{
  if (!_is_open)
  {
    try
      {
    connect();
      }
    catch(...)
      {
    throw;
      }
  }
  return std::string( mysql_get_host_info(&_mysql)); 
}

unsigned int Connection::get_protocol_version(void) throw(sqlerror)
{
  if (!_is_open)
  {
    try
      {
    connect();
      }
    catch(...)
      {
    throw;
      }
  }
  return mysql_get_proto_info(&_mysql);
}

std::string Connection::get_server_info(void)throw(sqlerror)
{
  if (!_is_open)
  {
    try
      {
    connect();
      }
    catch(...)
      {
    throw;
      }
  }
  return std::string( mysql_get_server_info(&_mysql));
}

unsigned long Connection::get_server_version(void) throw(sqlerror)

  if (!_is_open)
  {
    try
      {
    connect();
      }
    catch(...)
      {
    throw;
      }
  }
  return mysql_get_server_version(&_mysql);
}

void Connection::check_exception(void) throw(sqlerror)
{
  std::string is_null( mysql_error(&_mysql) );
  if (is_null != "")
    {
      try
    {
      throw sqlerror( boost::lexical_cast<std::string>( mysql_errno(&_mysql) ),is_null);
    }
      //catch boost lexical cast error
      catch(const boost::bad_lexical_cast& e)
    {
      throw sqlerror(e.what(),is_null);
    }
    }
}

void Connection::download(Table& target) throw(sqlerror)
{
  if (!_is_open)
    {
      try
      {
      connect();
      }
      catch(...)
      {
      throw;
      }
    }
  std::string cmd = target.get_create_cmd();
 
  //error occur
  if (mysql_real_query(&_mysql,cmd.c_str(),cmd.length()))
  {
      try
      {
    check_exception();
      }
      catch(...)
     {
       throw;
     }
  }
 
  MYSQL_RES* ptr_result = mysql_use_result(&_mysql);
  //error occur
  if (ptr_result == NULL)
  {
      try
      {
    check_exception();
      }
      catch(...)
      {
    throw;
      }
 }

   // fill field message
   unsigned int field_nums = mysql_num_fields(ptr_result);//no error
   MYSQL_FIELD* ptr_fields = mysql_fetch_fields(ptr_result);// no error
   std::vector<std::string>& field_list = target.get_fields();
   for(int i=0; i<field_nums; i++)
   {
     field_list.push_back(std::string(ptr_fields[i].name));
   }
  
   //fill row message
   MYSQL_ROW row;
   typedef std::map<int, std::string> map_row;
   std::vector< map_row >& row_list = target.get_rows();
   map_row currt_row;
  
   while ((row = mysql_fetch_row(ptr_result)))
   {
     for (int k=0; k<field_list.size(); k++)
     {
       currt_row[k] = boost::lexical_cast<std::string>(row[k]);
     }
     row_list.push_back(currt_row);
   }
  
   mysql_free_result(ptr_result);// no error  
}

void Connection::online_start(std::map<int, std::string>& row, const std::string& cmd) throw(sqlerror)
{
  if (!_is_open)
    {
      try
    {
      connect();
    }
      catch(...)
    {
      throw;
    }
    }

  //return 0 is success,or failure
  if (mysql_real_query(&_mysql,cmd.c_str(),cmd.length()))
  {
    //check exception
    try
   {
     check_exception();
   }
    catch(...)
   {
     throw;
   }
  }

 _ptr_result = mysql_use_result(&_mysql);// no error

 MYSQL_ROW current_row = mysql_fetch_row(_ptr_result);
 //error possablie occur
 if (current_row == NULL)
 {
   //check exception
   try
   {
     check_exception();
   }
   catch(...)
   {
     throw;
   }
 }

 for (int k=0; k<_num_fields; k++)
   {
     row[k] = current_row[k];
   }

}

void Connection::online_next(std::map<int, std::string>& row) throw(sqlerror)
{

 MYSQL_ROW current_row = mysql_fetch_row(_ptr_result);

 //error passablie occur
 if (current_row == NULL)
   {
     try
       {
     check_exception();
       }
     catch(...)
       {
     throw;
       }
   }
 for (int k=0; k<_num_fields; k++)
   {
     row[k] = current_row[k];
   }
}

bool Connection::online_is_eof(void)throw()
{
  if (!mysql_eof(_ptr_result))// api no error
    {
      return false;
    }
  else
    {
       mysql_free_result(_ptr_result);// auto free result,api no error
    }
}

unsigned long Connection::exceute(const std::string& cmd)throw(sqlerror)
{
  if (!_is_open)
  {
      try
    {
      connect();
    }
      catch(...)
    {
      throw;
    }
  }

  if (mysql_real_query(&_mysql, cmd.c_str(), cmd.length()))//return 0 is successful
  {
      try
      {
    check_exception();
      }
      catch(...)
     {
       throw;
     }
  }

  return mysql_affected_rows(&_mysql);//no error
}

const std::string& Connection::get_user(void)const throw()
{
  return _user;
}

const std::string& Connection::get_database(void)const throw()
{
  return _database;
}

const std::string& Connection::get_server(void)const throw()
{
  return _server;
}

const std::string& Connection::get_password(void)const throw()
{
  return _password;
}

void Connection::set_user(const std::string& user)throw()
{
  _user = user;
}

void Connection::set_database(const std::string& database)throw()
{
  _database = database;
}

void Connection::set_server(const std::string& server)throw()
{
  _server = server;
}

void Connection::set_password(const std::string& password)throw()
{
  _password = password;
}
 
INFO: pip is still looking at multiple versions of matplotlib to determine which version is compatible with other requirements. This could take a while. Downloading matplotlib-3.9.2-cp313-cp313-win_amd64.whl.metadata (11 kB) Downloading matplotlib-3.9.1.post1.tar.gz (36.1 MB) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╸━━━━━━ 30.7/36.1 MB 36.5 kB/s eta 0:02:29 WARNING: Connection timed out while downloading. WARNING: Attempting to resume incomplete download (30.7 MB/36.1 MB, attempt 1) Resuming download matplotlib-3.9.1.post1.tar.gz (30.7 MB/36.1 MB) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╸━━ 34.1/36.1 MB 8.9 kB/s eta 0:03:46 WARNING: Connection timed out while downloading. WARNING: Attempting to resume incomplete download (34.1 MB/36.1 MB, attempt 2) Resuming download matplotlib-3.9.1.post1.tar.gz (34.1 MB/36.1 MB) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 36.1/36.1 MB 10.9 kB/s 0:02:55 Installing build dependencies ... done Getting requirements to build wheel ... done Installing backend dependencies ... done Preparing metadata (pyproject.toml) ... error error: subprocess-exited-with-error × Preparing metadata (pyproject.toml) did not run successfully. │ exit code: 1 ╰─> [22 lines of output] + meson setup C:\Users\22609\AppData\Local\Temp\pip-install-_t2lmggr\matplotlib_3cc5ef11b7c44b96a61c74c2a2729bce C:\Users\22609\AppData\Local\Temp\pip-install-_t2lmggr\matplotlib_3cc5ef11b7c44b96a61c74c2a2729bce\.mesonpy-5x3rtjzz -Dbuildtype=release -Db_ndebug=if-release -Db_vscrt=md --native-file=C:\Users\22609\AppData\Local\Temp\pip-install-_t2lmggr\matplotlib_3cc5ef11b7c44b96a61c74c2a2729bce\.mesonpy-5x3rtjzz\meson-python-native-file.ini The Meson build system Version: 1.9.1 Source dir: C:\Users\22609\AppData\Local\Temp\pip-install-_t2lmggr\matplotlib_3cc5ef11b7c44b96a61c74c2a2729bce Build dir: C:\Users\22609\AppData\Local\Temp\pip-install-_t2lmggr\matplotlib_3cc5ef11b7c44b96a61c74c2a2729bce\.mesonpy-5x3rtjzz Build type: native build Program python3 found: YES (C:\Users\22609\AppData\Local\Python\bin\python3.EXE) WARNING: Failed to activate VS environment: Could not find C:\Program Files (x86)\Microsoft Visual Studio\Installer\vswhere.exe Project name: matplotlib Project version: 3.9.1.post1 ..\meson.build:1:0: ERROR: Unknown compiler(s): [['icl'], ['cl'], ['cc'], ['gcc'], ['clang'], ['clang-cl'], ['pgcc']] The following exception(s) were encountered: Running `icl ""` gave "[WinError 2] 系统找不到指定的文件。" Running `cl /?` gave "[WinError 2] 系统找不到指定的文件。" Running `cc --version` gave "[WinError 2] 系统找不到指定的文件。" Running `gcc --version` gave "[WinError 2] 系统找不到指定的文件。" Running `clang --version` gave "[WinError 2] 系统找不到指定的文件。" Running `clang-cl /?` gave "[WinError 2] 系统找不到指定的文件。" Running `pgcc --version` gave "[WinError 2] 系统找不到指定的文件。" A full log can be found at C:\Users\22609\AppData\Local\Temp\pip-install-_t2lmggr\matplotlib_3cc5ef11b7c44b96a61c74c2a2729bce\.mesonpy-5x3rtjzz\meson-logs\meson-log.txt [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. [notice] A new release of pip is available: 25.2 -> 25.3 [notice] To update, run: python.exe -m pip install --upgrade pip error: metadata-generation-failed × Encountered error while generating package metadata. ╰─> See above for output. note: This is an issue with the package mentioned above, not pip. hint: See above for details.分析一下错误原因
最新发布
11-28
#include <Arduino.h> // 基础Arduino功能 #include <Ethernet.h> // 以太网驱动 #include <SPI.h> #include <WiFi.h> // 网络事件处理 #include <ArduinoWebsockets.h> using namespace websockets; // W5500引脚配置 - 根据您的设置 #define ETH_CS_PIN 5 // 芯片选择引脚 #define ETH_SCLK_PIN 4 // 串行时钟引脚 #define ETH_MOSI_PIN 2 // 主输出从输入引脚 #define ETH_MISO_PIN 1 // 主输入从输出引脚 // 网络配置 byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED}; // MAC地址 const char* ws_server = "ws://socket.jnsywl.cn:80"; // WebSocket服务器地址 // WebSocket客户端 WebsocketsClient wsClient; void connectToWebSocket() { Serial.println("Connecting to WebSocket server..."); if (wsClient.connect(ws_server)) { Serial.println("WebSocket Connected!"); wsClient.send("ESP32-S3 Connected via W5500 Ethernet"); } else { Serial.println("Connection Failed!"); } // 设置消息回调 wsClient.onMessage([](WebsocketsMessage msg) { Serial.print("Received: "); Serial.println(msg.data()); }); } void setup() { Serial.begin(115200); while (!Serial); // 等待串口连接(仅用于调试) // 初始化SPI通信 SPI.begin(ETH_SCLK_PIN, ETH_MISO_PIN, ETH_MOSI_PIN, ETH_CS_PIN); // 初始化以太网连接 Ethernet.init(ETH_CS_PIN); // 指定CS引脚 Serial.println("Starting Ethernet connection..."); if (Ethernet.begin(mac) == 0) { Serial.println("Failed to configure Ethernet using DHCP"); if (Ethernet.hardwareStatus() == EthernetNoHardware) { Serial.println("Ethernet shield was not found."); } else if (Ethernet.linkStatus() == LinkOFF) { Serial.println("Ethernet cable is not connected."); } // 在此处添加失败处理逻辑 while (true) delay(1000); } // 打印网络信息 Serial.print("IP Address: "); Serial.println(Ethernet.localIP()); // 连接WebSocket connectToWebSocket(); } void loop() { // 维护以太网连接 switch (Ethernet.maintain()) { case 1: // 租失败 Serial.println("DHCP lease renewal failed"); break; case 2: // 租成功 Serial.println("DHCP lease renewed"); Serial.print("New IP Address: "); Serial.println(Ethernet.localIP()); // 重新连接WebSocket if (!wsClient.available()) connectToWebSocket(); break; case 3: // 绑定失败 Serial.println("DHCP rebind failed"); break; case 4: // 绑定成功 Serial.println("DHCP rebind successful"); Serial.print("New IP Address: "); Serial.println(Ethernet.localIP()); // 重新连接WebSocket if (!wsClient.available()) connectToWebSocket(); break; default: break; } // 处理WebSocket通信 if (wsClient.available()) { wsClient.poll(); // 每5秒发送心跳 static unsigned long lastSend = 0; if (millis() - lastSend > 5000) { if (wsClient.send("Eth Heartbeat")) { Serial.println("Heartbeat sent"); } else { Serial.println("Heartbeat failed"); } lastSend = millis(); } } else if (Ethernet.linkStatus() == LinkON) { // 尝试重新连接WebSocket Serial.println("WebSocket disconnected, attempting reconnect..."); connectToWebSocket(); delay(5000); } }这是我的代码,运行后能显示连接成功,但是紧接着就掉线16:38:37.342 -> WebSocket disconnected, attempting reconnect... 16:38:37.342 -> Connecting to WebSocket server... 16:38:37.342 -> Connection Failed! 16:38:42.375 -> WebSocket disconnected, attempting reconnect... 16:38:42.375 -> Connecting to WebSocket server... 16:38:42.375 -> Connection Failed! 16:38:47.387 -> WebSocket disconnected, attempting reconnect... 16:38:47.387 -> Connecting to WebSocket server... 16:38:47.387 -> Connection Failed! 16:38:52.351 -> WebSocket disconnected, attempting reconnect... 16:38:52.351 -> Connecting to WebSocket server... 16:38:52.351 -> Connection Failed! 16:38:57.357 -> WebSocket disconnected, attempting reconnect... 16:38:57.357 -> Connecting to WebSocket server... 16:38:57.357 -> Connection Failed! 16:39:02.503 -> WebSocket disconnected, attempting reconnect... 16:39:02.503 -> Connecting to WebSocket server... 16:39:02.503 -> Connection Failed! 16:39:07.379 -> WebSocket disconnected, attempting reconnect... 16:39:07.379 -> Connecting to WebSocket server... 16:39:07.379 -> Connection Failed!
09-03
xiaoyong@DZ0105952:~$ curl -H "Range: bytes=0-100" http://127.0.0.1:8081/download --output first_10.txt % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 100 101 100 101 0 0 97773 0 --:--:-- --:--:-- --:--:-- 98k xiaoyong@DZ0105952:~$ curl -H "Range: bytes=1-100" http://127.0.0.1:8081/download --output first_10.txt % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 99 100 99 99 0 0 19 0 0:00:05 0:00:05 --:--:-- 0 curl: (18) transfer closed with 1 bytes remaining to read xiaoyong@DZ0105952:~$ curl -H "Range: bytes=2-100" http://127.0.0.1:8081/download --output first_10.txt % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 97 99 97 97 0 0 19 0 0:00:05 0:00:05 --:--:-- 0 curl: (18) transfer closed with 2 bytes remaining to read xiaoyong@DZ0105952:~$ curl -H "Range: bytes=0-100" http://127.0.0.1:8081/download --output first_10.txt % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 100 101 100 101 0 0 88674 0 --:--:-- --:--:-- --:--:-- 98k xiaoyong@DZ0105952:~$ curl -H "Range: bytes=10-100" http://127.0.0.1:8081/download --output first_10.txt % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 89 91 89 81 0 0 16 0 0:00:05 0:00:05 --:--:-- 0 curl: (18) transfer closed with 10 bytes remaining to read xiaoyong@DZ0105952:~$ curl -H "Range: bytes=50-100" http://127.0.0.1:8081/download --output first_10.txt % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 1 51 0 1 0 0 0 0 --:--:-- 0:00:05 --:--:-- 0 curl: (18) transfer closed with 50 bytes remaining to read xiaoyong@DZ0105952:~$ curl -H "Range: bytes=50-100" http://127.0.0.1:8081/download --output first_10.txt % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 1 51 0 1 0 0 0 0 --:--:-- 0:00:05 --:--:-- 0 curl: (18) transfer closed with 50 bytes remaining to read xiaoyong@DZ0105952:~$ curl -H "Range: bytes=50-100" http://127.0.0.1:8081/download --output first_10.txt % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 1 51 0 1 0 0 0 0 --:--:-- 0:00:05 --:--:-- 0 curl: (18) transfer closed with 50 bytes remaining to read xiaoyong@DZ0105952:~$ curl -H "Range: bytes=0-100" http://127.0.0.1:8081/download --output first_10.txt % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 100 101 100 101 0 0 61811 0 --:--:-- --:--:-- --:--:-- 98k xiaoyong@DZ0105952:~$ curl -H "Range: bytes=10-100" http://127.0.0.1:8081/download --output first_10.txt % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 89 91 89 81 0 0 16 0 0:00:05 0:00:05 --:--:-- 0 curl: (18) transfer closed with 10 bytes remaining to read
07-12
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值