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`
Related
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.
Im having an issue connecting to QuestDB with libpqxx, i can establish a connection using the postgresql client as per the instructions here:
https://questdb.io/docs/guidePSQL
however, when i go to connect to QuestDB, using my simple program, that is more-or-less a slightly modified version of the standard "get me started" program:
https://github.com/jtv/libpqxx
#include <iostream>
#include <pqxx/pqxx>
int main(){
try
{
pqxx::connection C(
"user=admin "
"hostaddr=127.0.0.1 "
"password=quest "
"dbname=qdb"
"port=8812 ");
std::cout << "Connected to " << C.dbname() << std::endl;
pqxx::work W{C};
pqxx::result R{W.exec("SELECT name FROM employee")};
std::cout << "Found " << R.size() << "employees:\n";
for (auto row: R)
std::cout << row[0].c_str() << '\n';
std::cout << "Doubling all employees' salaries...\n";
W.exec0("UPDATE employee SET salary = salary*2");
std::cout << "Making changes definite: ";
W.commit();
std::cout << "OK.\n";
}
catch (std::exception const &e)
{
std::cerr << e.what() << '\n';
return 1;
}
return 0;
}
.. i get an error:
could not connect to server: Connection refused
Is the server running on host "127.0.0.1" and accepting
TCP/IP connections on port 5432?
what also complicates things possibly, is i cannot find anywhere pg_hba.conf ,are these even still a thing in version 10 of postgresql? i have /usr/lib/postgresql/10 but no config files.. and ive also searched the machine.. nothing found. any help would be much appreciated.
thankyou
The official documentation for libpqxx states that:
The connection string consists of attribute=value pairs separated by spaces, e.g. "user=john password=1x2y3z4". reference
Your connection string is:
pqxx::connection C(
"user=admin "
"hostaddr=127.0.0.1 "
"password=quest "
"dbname=qdb"
"port=8812 ");
You are missing a space after qdb, so the correct connection string is:
pqxx::connection C(
"user=admin "
"hostaddr=127.0.0.1 "
"password=quest "
"dbname=qdb "
"port=8812 ");
I just tried it and it works fine for me.
On a second hand, the following SQL statement:
W.exec0("UPDATE employee SET salary = salary*2");
Will not work, UPDATE is not supported yet by QuestDB. You can find more details about SQL support on the official documentation, here.
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.
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?
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