d aGetting error while connecting to Postgres via dev c++ - postgresql

I am trying to get connected to Postgres database via Dev-c++ (Windows application and not console) for executing queries, but I am continuously getting errors.
I went through the following link:
http://www.tutorialspoint.com/postgresql/postgresql_c_cpp.htm
and added the below code to that of mine:
#include <iostream>
#include <pqxx/pqxx>
using namespace std;
using namespace pqxx;
int main(int argc, char* argv[])
{
try{
connection C("dbname=testdb user=postgres password=cohondob \
hostaddr=127.0.0.1 port=5432");
if (C.is_open()) {
cout << "Opened database successfully: " << C.dbname() << endl;
} else {
cout << "Can't open database" << endl;
return 1;
}
C.disconnect ();
}catch (const std::exception &e){
cerr << e.what() << std::endl;
return 1;
}
}
But got error stating:
'No such file or directory
#include
Compilation terminated'
Please, Can anyone help me get through this?
is there any other possible way to get connected?

Related

Memory leak in C++ VScode with mingw-64 ,CRT: _CrtDumpMemoryLeaks() not showing the memory leak

I am on windows 11 using VScode to run a C++ code with ming-w64.
I have installed ming-w64 following all these steps
I am running a code that has a deliberate memory leak to see if there is a report by _CrtDumpMemoryLeaks().
this is my code:
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
#include <iostream>
#ifdef _DEBUG
#define DBG_NEW new ( _NORMAL_BLOCK , __FILE__ , __LINE__ )
// Replace _NORMAL_BLOCK with _CLIENT_BLOCK if you want the
// allocations to be of _CLIENT_BLOCK type
#else
#define DBG_NEW new
#endif
using namespace std;
int main()
{
_CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );
_CrtSetReportMode( _CRT_WARN, _CRTDBG_MODE_DEBUG );
_CrtSetReportFile( _CRT_WARN, _CRTDBG_FILE_STDOUT );
_CrtSetReportMode( _CRT_ERROR, _CRTDBG_MODE_FILE );
_CrtSetReportFile( _CRT_ERROR, _CRTDBG_FILE_STDOUT );
_CrtSetReportMode( _CRT_ASSERT, _CRTDBG_MODE_FILE );
_CrtSetReportFile( _CRT_ASSERT, _CRTDBG_FILE_STDOUT );
int *i2 = new int(2);
cout << "address of i2 :" << i2 << endl;
bool check = _CrtDumpMemoryLeaks();
cout << "MEMORY check :" << check << endl;
cout << "After CrtDumpMemoryLeaks" << endl;
}
This is the TERMINAL:
PS C:\Users\שראל\Desktop\C_proj\projects\helloworld> & 'c:\Users\שראל\.vscode\extensions\ms-vscode.cpptools-1.9.7\debugAdapters\bin\WindowsDebugLauncher.exe' '--stdin=Microsoft-MIEngine-In-o0zd5lqu.up2' '--stdout=Microsoft-MIEngine-Out-gva0ndx0.ycm' '--stderr=Microsoft-MIEngine-Error-eec2m2xg.4x5' '--pid=Microsoft-MIEngine-Pid-fakhxofs.oyp' '--dbgExe=C:\msys64\mingw64\bin\gdb.exe' '--interpreter=mi'
address of i2 :0x190a9ff1a90
MEMORY check :0
After CrtDumpMemoryLeaks
And the OUTPUT is empty.
I don't understand what I am doing wrong here.

How fix strange syntax problem when using execute function?

I met an error when trying to use a function called execute to use one database. The information shows me that's about syntax, but I don't think so.
The following is my critical code and important information about the error.
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'u' at line 1
#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<string>
#include "mysql_connection.h"
#include <mysql_driver.h>
#include <cppconn/driver.h>
#include <cppconn/exception.h>
#include <cppconn/resultset.h>
#include <cppconn/statement.h>
using namespace std;
using namespace sql;
int main()
{
try {
sql::mysql::MySQL_Driver driver;
cout<<" driver "<<endl;
sql::Connection *con = NULL;
cout<<" con"<<endl;
sql::Statement *stmt;
cout<<" stmt"<<endl;
sql::ResultSet *res;
cout<<" res"<<endl;
/* Create a connection */
//driver = sql::mysql::MySQL_Driver::MySQL_Driver();
SQLString ip_port("localhost:3306");
cout<<"some debug string"<<endl;
SQLString user("debian-sys-maint");
SQLString password("fTlykRye1LwttC8f");
con = driver.connect(ip_port, user, password);
assert(con!=NULL);
cout<<" root"<<endl;
/* Connect to the MySQL test database */
SQLString schema("account");
//con->setSchema(schema);
cout<<" table"<<endl;
stmt = con->createStatement();
cout<<" table*2"<<endl;
assert(stmt!=NULL);
SQLString db("use account");
stmt->execute(db);
res = stmt->executeQuery("SELECT * from user");
while (res->next()) {
cout << "\t... MySQL replies: ";
/* Access column data by alias or column name */
cout << res->getString("name") << endl;
cout << "\t... MySQL says it again: ";
/* Access column data by numeric offset, 1 is the first column */
cout << res->getString("password") << endl;
}
delete res;
delete stmt;
delete con;
} catch (sql::SQLException &e) {
cout << "# ERR: SQLException in " << __FILE__;
cout << "(" << __FUNCTION__ << ") on line "<<endl;
cout << "# ERR: " << e.what();
cout << " (MySQL error code: " << e.getErrorCode();
cout << ", SQLState: " << e.getSQLState() << " )" << endl;
cout<<"\n";
}
cout << endl;
return EXIT_SUCCESS;
}
I was confused that why the information was not about the sentence "use account". Instead, it was about "u". Thanks very much.
USER is a reserved word/keyword in MySQL.
You should delimit your field names with backticks to avoid problems:
SELECT * FROM `user`

boost asio SO_REUSEPORT

I'm working on a multi-processes socket server with the boost library.
Each process run a io_service.
I want to this processes all accept on the same port.
I know SO_REUSEPORT (after linux kernel 3.9) will help.
like this python script
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
s.bind(('0.0.0.0', 9091))
s.listen(1)
while True:
conn, addr = s.accept()
print "new connection"
while True:
data = conn.recv(100)
print "got data", data
if not data or data == 'exit':
break
conn.close()
But I don't know how to use this option in boost asio io_service ?
For people reading this in 2019: Asio now includes a workaround in boost/asio/detail/impl/socket_ops.ipp:
#if defined(__MACH__) && defined(__APPLE__) \
|| defined(__NetBSD__) || defined(__FreeBSD__) || defined(__OpenBSD__)
// To implement portable behaviour for SO_REUSEADDR with UDP sockets we
// need to also set SO_REUSEPORT on BSD-based platforms.
if ((state & datagram_oriented)
&& level == SOL_SOCKET && optname == SO_REUSEADDR)
{
call_setsockopt(&msghdr::msg_namelen, s,
SOL_SOCKET, SO_REUSEPORT, optval, optlen);
}
#endif
So, socket_->set_option(udp::socket::reuse_address(true)); will set the SO_REUSEPORT option automatically if needed.
Following on from how boost/asio/socket_base.hpp defines reuse_address, I did it like this:
typedef boost::asio::detail::socket_option::boolean<SOL_SOCKET, SO_REUSEPORT> reuse_port;
socket_.set_option(reuse_port(true));
Answer by my own.
#include <iostream>
#include <string>
#include <array>
#include <boost/asio.hpp>
#include <arpa/inet.h>
using boost::asio::ip::tcp;
int main()
{
boost::asio::io_service io;
tcp::acceptor acceptor(io);
acceptor.open(tcp::v4());
int one = 1;
setsockopt(acceptor.native_handle(), SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &one, sizeof(one));
acceptor.bind(tcp::endpoint(tcp::v4(), 9091));
acceptor.listen();
std::cout << "start" << std::endl;
for(;;)
{
tcp::socket socket(io);
acceptor.accept(socket);
std::cout << "new connections" << std::endl;
for(;;)
{
std::array<char, 4> buf;
boost::system::error_code error;
boost::asio::read(socket, boost::asio::buffer(buf), error);
if(error)
{
std::cout << "read error: " << error << std::endl;
break;
}
std::cout << "read: " << std::string(buf.data()) << std::endl;
}
}
}
The HTTP server example shows one way: http://www.boost.org/doc/libs/1_60_0/doc/html/boost_asio/example/cpp11/http/server/server.cpp
// Open the acceptor with the option to reuse the address (i.e. SO_REUSEADDR).
boost::asio::ip::tcp::resolver resolver(io_service_);
boost::asio::ip::tcp::endpoint endpoint = *resolver.resolve({address, port});
acceptor_.open(endpoint.protocol());
acceptor_.set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
acceptor_.bind(endpoint);
acceptor_.listen();
IIRC there's also an acceptor constructor that takes a boolean argument to set the reuse flag.

WINSOCK error 10022 on listen when include thread

I am implementing a simple multithreaded FTP client server where I am facing a problem which is strange for me( as I am no master in C++ and threads).
The code I have written works normally until I #include <thread>.
Once I include the thread class the program fails on listen and gives a 10022 error. (I haven't done anything related to threads yet, only import).
Below is the code. The method is called from main().
#include <winsock2.h>
#include <ws2tcpip.h>
#include <process.h>
#include <winsock.h>
#include <iostream>
#include <windows.h>
#include <fstream>
#include <string>
#include <stdio.h>
#include <time.h>
#include <thread>
using namespace std;
void initializeSockets()
{
try{
logEvents("SERVER", "Initializing the server");
WSADATA wsadata;
if (WSAStartup(0x0202,&wsadata)!=0){
cout<<"Error in starting WSAStartup()\n";
logEvents("SERVER", "Error in starting WSAStartup()");
}else{
logEvents("SERVER", "WSAStartup was suuccessful");
}
gethostname(localhost,20);
cout<<"hostname: "<<localhost<< endl;
if((hp=gethostbyname(localhost)) == NULL) {
cout << "gethostbyname() cannot get local host info?"
<< WSAGetLastError() << endl;
logEvents("SERVER", "Cannot get local host info. Exiting....");
exit(1);
}
//Create the server socket
if((serverSocket = socket(AF_INET,SOCK_STREAM,0))==INVALID_SOCKET)
throw "can't initialize socket";
//Fill-in Server Port and Address info.
serverSocketAddr.sin_family = AF_INET;
serverSocketAddr.sin_port = htons(port);
serverSocketAddr.sin_addr.s_addr = htonl(INADDR_ANY);
//Bind the server port
if (bind(serverSocket,(LPSOCKADDR)&serverSocketAddr,sizeof(serverSocketAddr)) == SOCKET_ERROR)
throw "can't bind the socket";
cout << "Bind was successful" << endl;
logEvents("SERVER", "Socket bound successfully.");
if(listen(serverSocket,10) == SOCKET_ERROR)
throw "couldn't set up listen on socket";
else
cout << "Listen was successful" << endl;
logEvents("SERVER", "Socket now listening...");
//Connection request accepted.
acceptUserConnections();
}
catch(char* desc)
{
cerr<<str<<WSAGetLastError()<<endl;
logEvents("SERVER", desc);
}
logEvents("SERVER", "Closing client socket...");
closesocket(clientSocket);
logEvents("SERVER", "Closed. \n Closing server socket...");
closesocket(serverSocket);
logEvents("SERVER", "Closed. Performing cleanup...");
WSACleanup();
}
int main(void){
initializeSockets();
return 0;
}
I have read the thread Winsock Error 10022 on Listen but I don't think that this has solution to my problem.
Error 10022 is WSAEINVAL. The documentation for listen() clearly states:
WSAEINVAL
The socket has not been bound with bind.
The reason your code stops working when you add #include <thread> is because your call to bind() is being altered to no longer call WinSock's bind() function, but to instead call the STL's std::bind() function. Your using namespace std statement is masking that issue (this is one of many reasons why using namespace std is such a bad practice - teach yourself to stop using that!).
So you need to either:
get rid of using namespace std.
qualify bind() with the global namespace so it calls WinSock's function:
if (::bind(...) == SOCKET_ERROR)

replace the text with pre and post string

I have file in which there are certian lines which have common string:
_report_file <<
SO the text around this above can be any thingbut it ends with semiclon(;)
for eg see the line below:
CACUP_updater::_report_file << "The job has terminated." << endl;
another example of the line can be:
_report_file << "The job is reading." << endl;
i need to append abc; as pre string and xyz; as post string to that line so that the line looks like
abc;CACUP_updater::_report_file << "The job has terminated." << endl;xyz;
basically i want to search for "_report_file <<",select the complete line and pre and post append some text.
how can i do this in sed or perl or awk.
A perl way:
perl -anE 'chomp;s/^(.*?::_report_file <<.*;)$/abc;$1xyz;/;say;' foo.txt > foo2.txt
or
perl -ane 'chomp;s/^(.*?::_report_file <<.*;)$/abc;${1}xyz;/;print "$_\n";' foo.txt > foo2.txt
$ perl -i.bak -n -e 'print "abc;${_}xyz;"' your_file_here
That'll give you a backup copy of the file too.
awk '/_report_file <</{$0="abc;" $0 "xyz;"}{print}'
perl -pi.bak -e 's{.*_report_file <<.*}{abc;$&xyz;}' file_name_here
Edit in response to your updated question. I think you're doing it wrong :)
I suggest you do it this way instead:
#!/usr/bin/perl
use strict;
use warnings;
while(<>)
{
s/([\w]+::)?_report_file\s*<<\s*(.*);/CACUP_REPORT($2);/go;
print
}
That way, you can, in C++, define a macro like
#define CACUP_REPORT(message) do { \
/* abc; */ \
::CACUP_updater::_report_file << message; \
/* xyz; */ } while (false)
But Why?
You can read all about safe macros elsewhere 1.
You get way more flexibility. You can later change all instances at one point.
You can delegate to a a function
You could declare a temporary stringstream and write the resulting text to a whole other medium (network? fwrite? memory buffer? two streams?).
You could make the logging conditional depending on a global falg without having to duplicate the check for it throughour your code.
Well you get it: it pretty much the DRY principle.
Sample input:
#include <iostream>
using namespace std;
namespace CACUP_updater
{
std::ostream& _report_file = std::cout;
void start_reading()
{
_report_file << "The job is reading." << endl;
}
}
int main()
{
CACUP_updater::_report_file << "The job is starting." << endl;
CACUP_updater::start_reading();
CACUP_updater::_report_file << "The job has terminated." << endl;
}
Sample output:
The result of, e.g. perl -i.bck test.cpp is 2:
#include <iostream>
using namespace std;
namespace CACUP_updater
{
std::ostream& _report_file = std::cout;
void start_reading()
{
CACUP_REPORT("The job is reading." << endl);
}
}
int main()
{
CACUP_REPORT("The job is starting." << endl);
CACUP_updater::start_reading();
CACUP_REPORT("The job has terminated." << endl);
}
Some ideas for implementations of the macro:
This shows how you can
use a temporary stream to stringify
print to more than one output stream, conditionally
handle exceptions properly inline
add a datetime stamp (only for writing to the log file, not stderr)
of course, there is more than enough room to accomodate any abc; or xyz; you had in mind :)
.
#include <iostream>
#include <sstream>
#include <fstream>
using namespace std;
static bool _verbose = false;
#define CACUP_REPORT(message) do { \
std::stringstream ss; \
ss << message; \
::CACUP_updater::log_helper(ss.str()); \
} while (false)
namespace CACUP_updater
{
std::string getdatetime() { return "YYYY/MM/DD - HH:MM:SS.mmm"; } // demo only
void log_helper(const std::string& msg)
{
try
{
std::ofstream ofs("/tmp/myprogram.log", std::ios_base::app);
ofs << getdatetime() << "\t" << msg;
ofs.flush();
ofs.close();
// log errors always to stderr,
// and all other messages if verbose is set
if (_verbose || std::string::npos != msg.find("ERROR"))
std::cerr << msg << std::endl;
} catch(std::exception& e)
{
std::cerr << "Unhandled error writing to log: '" << e.what() << std::endl;
}
}
void start_reading()
{
CACUP_REPORT("The job is reading." << endl);
}
}
int main()
{
CACUP_REPORT("The job is starting." << endl);
CACUP_updater::start_reading();
CACUP_REPORT("The job has terminated." << endl);
}
The output to the file is:
YYYY/MM/DD - HH:MM:SS.mmm The job is starting.
YYYY/MM/DD - HH:MM:SS.mmm The job is reading.
YYYY/MM/DD - HH:MM:SS.mmm The job has terminated.
The output to the stderr depends on the verbose flag
1 just imagine what would happen if if (b) _report_file << "ok!" << std::endl; ?
2 note that a backup file is created: test.cpp.bck