connect to sql in c++? - c++

I want to connect to sql using c++.
I have g++ (sparc-sun-solaris2.10-g++) installed on my UNIX machine and the sql version is SQL*Plus: Release 10.2.0.4.0.
I want to write a c++ code by which I want to connect to sql.
Using shell script I can easily connect to the DB but using c++ I don't know how to do it.
Thanks .
I have this piece of code but this is failing while I compile :
error :
Creating library libr9.so 20110308_083331
ld: fatal: file /tlmsr1/tlm/rt/kimi/proj/c9rprOG/crp/templates.a: open failed: No such file or directory
ld: fatal: file /tlmsr1/tlm/rt/kimi/proj/c9rprOG/crp/templates.a: open failed: No such file or directory
ld: fatal: File processing errors. No output written to /tlmsr1/tlm/rt/kimi/proj/c9rprOG/lib/libcrpr9.so
gmake: * [libr9.so] Error 1
code :
#include <stdlib.h>
#include <occi.h>
#include <iostream>
using namespace oracle::occi;
using namespace std;
class testOcci
{
private:
Environment *env;
Connection *conn;
public:
testOcci (string user, string passwd, string db)
{
env = Environment::createEnvironment (Environment::DEFAULT);
conn = env->createConnection (user, passwd, db);
}
/**
* Destructor for the occi test case.
*/
~testOcci ()
{
env->terminateConnection (conn);
Environment::terminateEnvironment (env);
} // end of ~testOcci ()
};
int main(void)
{
string user="sbsdb6";
string passwd="sbsdb6";
string db="ABPDV";
testOcci *demo = new testOcci (user, passwd, db);
cout << "Creation Successful" << endl;
delete (demo);
cout << "Deletion Successful" << endl;
return 0;
}

Since it seems as though you mean Oracle when you say sql I think you want to try OCCI . In that case this link might help.
But... using OCCI is quite different from connecting to Oracle with a shell script via SQL*Plus.

You might also take a look at those two libs.
OTL and SOCI.
I used both in some projects and they worked fine for me.

You need to use ODBC libraries to connect and retrieve data from a RDBMS. This seems to be a good starting point.

Try the class named CDatabase.
Create a connection to the databse.
And a function named ExecuteSQL() using which u can execute queries.
For fetching the results u have CResultSet class.
If you find difficulty post here.. i wil send u the sample.
thanks
Arun P.

Related

ora-1017 invalid username/password; logon denied using occi connection

I'm getting an ora-1017 error when trying to connect to my local oracle database(version 11.2.0.3) on an oracle linux version 5 virtual machine using occi.
Connection code piece:
user = "MY_USERNAME";
passwd = "MY_PASSWORD";
db = "localhost:1521/my_instance_name";
env = Environment::createEnvironment(Environment::DEFAULT);
try
{
con = env->createConnection(user, passwd, db);
}
catch (SQLException& ex)
{
cout << ex.getMessage();
exit(EXIT_FAILURE);
}
- I can connect to the schema using sqlplus.
- I tried setting SEC_CASE_SENSITIVE_LOGON to false, didn't help.
- The schema was created using uppercase username and password, I'm giving my variables uppercase values too, and as far as I know OCCI casts the credentials to uppercase anyway so it should work.
- ORACLE_SID environment variable is properly set, as well as the tnsnames.ora data too.
- By the way, this code was tested first on my host pc(win10) using visual studio 2010, and it was working properly, but not on my linux virtual machine(using virtualbox). I tried it using the host stated in tnsnames.ora and localhost both, still getting the same issue, but sqlplus lets me connect using both localhost and the tnsnames host.
I tried everything I could find on google, but still nothing, so if anyone has any useful tips it would be highly appreciated.
Turned out I needed to add the -D_GLIBCXX_USE_CXX11_ABI=0 flag to the compile command, it works now.

Trying to connect to a MariaDB database in google-cloud but cant connect nor show any error report

I'm trying to connect a simple program to a MariaDB database created in a VM in Google Cloud.
The VM already has a working installation of MariaDB and a small working demo DB.
The code used is the following:
#include <mysql++/mysql++.h>
#include <iostream>
// Nombres
using namespace std;
using namespace mysqlpp;
// INICIO
int main ()
{
//Declara variables
char server[] = "104.197.112.189:3306";
char user[] = "root";
char pass[] = "xxxxxxxx";
char db[] = "resst";
unsigned int i;
//conexión
Connection con;
con.connect("", server, user, pass);
con.select_db(db);
//pedido SQL
string consulta = "select * from productos";
//realización de pedido
Query pedido = con.query(consulta);
StoreQueryResult resp = pedido.store();
Row fila;
for (i=0;i<resp.num_rows();i++)
{
cout << "res " << i+1 << " " << resp[i]["nombre"] << endl;
}
con.disconnect();
return 0;
}
This code works perfectly with an exact copy of this DB created in my localhost, and prints a result when I run it locally.
On the other hand when I run it with the connection to the online DB, the program shows absolutely nothing, no window, no line, no error, just the terminal where I run it with a blank line, so i dont know where to start looking. The error reports are active, and show any other errors that happen.
Please,can anybody give me a hint on this?
Ok for someone with a similar problem, Mariadb (probably also works for MySQL) and Google Cloud have all external connections locked by default. It can be solved in two steps:
In google cloud: going into the developer console/ your project/ connections/ firewall rules and create a new rule allowing port 3306, that is default for MySQL and Mariadb.
In Mariadb: change my.conf, following the first part of this tutorial.
And that's it, now it's working. Thanks to #mrunion for the help.

xerces-c library function returns NULL when daemon ran via inetd

My application is an server application that accepts some predefined commands from user and displays respective output that is taken from XML files present at the server end.
For parsing XML file I am using xerces-c library version 3.1.2 from apache. The application works fine when ran manually on a terminal.
But I wanted to run the application through telnet on a network so that I can give inputs to the application via telnet and receive output on a remote system too. For this I used inetd super server and added below line in inetd.conf:
vterm stream tcp nowait root /path/to/my/binary/vterm vterm
Then added below line in /etc/services to make it listen on port 5000
vterm 5000/tcp
After that when I tried to connect to my application I used to get below message:
msatyam#sabayon ~/programming/cpp/xml $ telnet localhost 5000
Trying ::1...
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
Connection closed by foreign host.
When the above connection closed message came I thought I have not configured properly my application with inetd. So, I replaced my binary with a simple binary which didn't used any extra libraries. Just simple cin's and cout's, which worked perfectly fine.
Then it turns out to be something wrong with my application so for this I put whole lot of cout's to identify what actually is happening. With this I found that one of the xerces-c XML parsing library function is returning NULL and with this NULL reference I am trying to call a function in line below which is making my application dump as soon as it starts.
But the thing is the same function is working fine when I run my application manually on a terminal. Full application is bit big so I have created a demo code which reproduces the problem. Here is my code:
#include <xercesc/util/PlatformUtils.hpp>
#include <xercesc/parsers/XercesDOMParser.hpp>
#include <xercesc/dom/DOMDocument.hpp>
#include <xercesc/dom/DOMElement.hpp>
#include <iostream>
using namespace std;
using namespace xercesc;
int main()
{
try
{
// init xerces XML Parser library
XMLPlatformUtils::Initialize();
}
catch (const XMLException& ex)
{
cerr << ex.getMessage() << endl;
}
// parse a XML file
XercesDOMParser* parser = new XercesDOMParser();
try
{
parser->parse("sample.xml");
}
catch (const XMLException& ex)
{
cerr << ex.getMessage() << endl;
}
// get the document reference
DOMDocument* doc = parser->getDocument();
if (doc == NULL)
{
cout <<"Doc is NULL" << endl;
}
// else do stuff further
// like get root element
DOMElement* root = doc->getDocumentElement();
// print node name
string name = XMLString::transcode(root->getTagName());
cout << "Name: " << name << endl;
XMLPlatformUtils::Terminate();
return 0;
}
The above code when compiled and ran manually does not go into that if condition which says "Doc is NULL" and successfully prints the root element tag name, but when I run this application behind inetd and when I telnet to it I am able to see "Doc is NULL" statement and after that same message "Connection closed by foreign host." as my application would be probably dumping.
I am a bit out of brains now as I am not sure where to look exactly. As same code works when ran manually but not through inetd.
So, I am thinking do we need to take some special attention while executing processes via inetd that uses shared libraries, like here I am using xerces-c shared library for XML parsing.
Or What else could be possibly wrong with my understanding or my code.
How come the same library functions works perfectly fine when application ran manually and not working when ran via inetd?
I tried the same using xinetd instead of inetd but same results.
As you have proven yourself, the working directory is / when you start your tool via inetd. But your XML file is not in the root directory of your system. You can hardwire the full path into your application. A better solution would be to pass the location of your file(s) as a parameter.

C++ connecting VS to Oracle

#include<iostream>
#include<iomanip>
#include<occi.h>
#include<string>
using namespace std;
using namespace oracle::occi;
int main (void){
string utilizador ="B3_1";
string password ="B3_1";
string bd ="gandalf.dei.isep.ipp.pt:1521/pdborcl";
try{
Environment *env;
Connection *ligacao;
Statement *instrucao;
env = Environment::createEnvironment (Environment::DEFAULT);
ligacao = env->createConnection (utilizador, password, bd);
cout <<"BDdad: a ligar ..."<< endl;
}catch(SQLException erro){
cerr <<"Erro: "<< erro.getMessage () << endl;}
cin.get();
return 0;
}
For this college project I need to connect Visual Studio 2012 to Oracle in order to interact with the database through VS. The problem is, all my workgroup can connect without any errors but in my case it's slightly different. I get a SQL Exeception in the line "env = Environment::createEnvironment (Environment::DEFAULT);". The error code is 1804, and the message it displays is "error while trying to retrieve text for error ORA-01804". I thought it could be the paths but I have the same as my friends and they can connect and I don't. Have this ever happened or is it normal ?
EDIT:
My teacher advised me to change the version of the Visual Studio 2012. I had the Ultimate version and he told to use the Express to see if works. Already did that and the result is the same. I looked all over the internet and couldn't find a straight answer to my problem.
Error code #32104 indicates that an error occurred in the call but the actual error message could not be retrieved. Essentially this means that Environment::createEnvironment failed then tried to acquire message associated with the error. When it couldn't find it the 32104 error was returned instead.
Because of this the exact cause of the error may be difficult to determine. I do suggest that you ensure both ORACLE_HOME and ORACLE_SID are defined in your shell environment.

Application crash after using mysql_fetch_row

I got a problem regarding simple MySQL function which is mysql_fetch_row when ever I use it, my application will crash with it will go to the point when its executing.
No matter what query I would run it will crash. The core dump says following:
(gdb) bt full
#0 0x2866397f in mysql_store_result () from /usr/home/ld/application
#1 0x28637905 in main () from /usr/home/ld/application
#2 0x08441d3a in CRC_GetCodeSize20 ()
The code looks simple:
int main()
{
MYSQL *conn; // the connection
MYSQL_RES *res; // the results
MYSQL_ROW row; // the results row (line by line)
struct connection_details mysqlD;
mysqlD.server = "localhost"; // where the mysql database is
mysqlD.user = "mysqlusername"; // the root user of mysql
mysqlD.password = "mysqlpassword"; // the password of the root user in mysql
mysqlD.database = "mysql"; // the databse to pick
conn = mysql_connection_setup(mysqlD);
res = mysql_perform_query(conn, "select 1, 2");
printf("Result:\n");
while ((row = mysql_fetch_row(res)) !=NULL)
printf("%s\n", row[0]);
mysql_free_result(res);
mysql_close(conn);
return 0;
}
What is the problem?
edit
mysql_perform_query:
MYSQL_RES* mysql_perform_query(MYSQL *connection, char *sql_query)
{
if (mysql_query(connection, sql_query))
{
printf("MySQL query error : %s\n", mysql_error(connection));
exit(1);
}
return mysql_use_result(connection);
}
Ok. So I have spent quite some time to reproduce this problem. I assume you took the example from this tutorial: http://www.codingfriends.com/index.php/2010/02/17/mysql-connection-example/ since it's exactly the same.
Steps taken:
cd /usr/ports/databases/mysql56-client && make install
Copy pasted the exact code from the above tutorial to test.cpp
g++ -I/usr/local/include/mysql -L/usr/local/lib/mysql -lmysqlclient test.cpp
./a.out
Output:
Mysql tables in database:
entry
old
I used my remote mysql server and a test account. First I made sure I can connect to it via console mysql -h mydomain.com -u test -p
The program seems to work normally. The only thing I noticed is that sometimes it takes 1 second to execute while other times it takes up to 10 seconds for whatever reason.
Built on PC-BSD Isotope Edition (9.1 RELEASE) with up to date port tree.
So now there are 2 people with successful build (me and your friend). Code being the same the only thing I can think of going wrong is the libmysqlclient.so library. Try to update your port tree and do a fresh build. Or maybe try a different version.
You could try viewing the registered *port* using the netstat command , because the reason it might be crashing is, you are using an already registered port for your dbase. Check for that.
Also if you find out working on an already registered port, try changing the port number in the S/w along with that you have to remove the value from the registry as well(regedit) .(Sometimes it uses the shadow port , so need to do that).
Also check for null in your "conn", Somehow maybe you arn't able to initiate a connection. (connection pool exhaustion?? Very doubtful ).