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 ).
Related
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.
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.
I am currently using C++ to write directly to a mySQL database, the program will write the first 151 items in the data base but as soon as it gets to number 152 it fails to connect to the data base and throws this exact error:
Unhandled exception at 0x6188F1F9 (libmysql.dll) in Project1.exe: 0xC0000005: Access violation reading location 0x000003B0
I have no idea what this means and cannot seem to find anything on the internet about it. Below I will post the code that writes to the DB. Again though I will say that it is working just fine up until number 152.
void writeToDB(string coordString, string time, string id){
MYSQL *connect; // Create a pointer to the MySQL instance
connect=mysql_init(NULL); // Initialise the instance
/* This If is irrelevant and you don't need to show it. I kept it in for Fault Testing.*/
if(!connect) /* If instance didn't initialize say so and exit with fault.*/
{
fprintf(stderr,"MySQL Initialization Failed");
}
/* Now we will actually connect to the specific database.*/
connect=mysql_real_connect(connect,SERVER,USER,PASSWORD,DATABASE,0,NULL,0);
/* Following if statements are unneeded too, but it's worth it to show on your
first app, so that if your database is empty or the query didn't return anything it
will at least let you know that the connection to the mysql server was established. */
if(connect){
printf("Connection Succeeded\n");
}
else{
printf("Connection Failed!\n");
return;
}
MYSQL_RES *result; /* Create a pointer to recieve the return value.*/
MYSQL_ROW row; /* Assign variable for rows. */
std::string strSql = "INSERT INTO locationtime (id, dateTime, location) VALUES ('" + id + "','" + time + "','" + coordString + "')";;
const char* sql = strSql.c_str();
mysql_query(connect, sql);
/* Send a query to the database. */
mysql_close(connect); /* Close and shutdown */
}
EDIT: Okay so I was able to get it to stop throwing the error, however it is still just mysteriously refusing to connect to the DB, I did test it with a PHP script instead and got 800+ values in the table with no issue at all. Im not sure what the issue is at all!
If the mysql_real_connect() had failed you should also put a return; or exit(1) after the printf("Connection Failed!\n");:
if(connect) {
printf("Connection Succeeded\n");
}
else {
printf("Connection Failed!\n");
return; // <<<
}
Otherwise your program will likely crash, without even you could see the error notification printed.
To check what actually was going wrong with the mysql_real_connect() function (and maybe give some more useful information than just "Connection Failed!\n"), you can use the mysql_errno() function. A list of the error codes relevant for this function can be found here.
Another possibility is you are passing invalid or empty data to the INSERT statements. Put some integrity checks for the data passed from coordString, time, id.
Okay so I finally got the answer after I had a second pair of eyes debugging with me.
In my function that actually writes to the database when the connection is actually successful, the mysql_close(); function was written AFTER the return statements. So it was all on me with a simple error that I over looked many times.
Thanks for all the help from the commenters and the answer I got!
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.
When I closed MySql server, how can I understand that mysql server is gone away from my Qt program?
Edit:
Here my trial:
When I close MySql, I get these results, and I can't catch that MySql is closed.
My Code Snippet is
QSqlQuery query(db);
query.exec("SELECT * From RequestIds");
qDebug()<<query.lastError();
qDebug()<<db.lastError()<<QTime::currentTime();
qDebug()<<db.isOpen();
qDebug()<<db.isValid();
and output is:
QSqlError(2006, "QMYSQL: Unable to execute query", "MySQL server has gone away")
QSqlError(-1, "", "") QTime("14:22:58")
true
true
I don't understand why db.isOpen() returns true.
There is a bug related with QSqlDatabase::isOpen() in Qt.
https://bugreports.qt.io/browse/QTBUG-223
Your program has no idea of its surroundings. If something changes, you may be able to have the OS notify your program, or you'll have to test yourself.
If the database connection closes before your program, the status from the connection should return some kind of error code. You are checking status from the connection functions?
Write a simple program that opens a window and upon the click of a button, writes to the database. After writing to the database, the program should display the status in the window. Run your program. Press button to get the "controlled" response. Close the database then click on the button again.
You may be able to do this with a debugger, depending on the ability of the debugger & OS to queue up messages.
QSqlQuery::lastError() should give you an error if your query via QSqlQuery::exec() has failed. Also QSqlDatabase::isOpen() should report the state of your connection, QSqlDatabase::lastError() is also available
You can use isOpenError to determine whether opening the initial database connection was successfull. I agree that isOpen returning true is confusing.
To monitor the database connection I repeatedly try to open and close a lightweight MySQL connection (e.g. every 3 seconds):
#include <mysql/mysql.h>
mysql_init(&connection);
MYSQL *result = mysql_real_connect(&connection,
host.isNull() ? static_cast<const char *>(0) : host.toLocal8Bit().constData(),
user.isNull() ? static_cast<const char *>(0) : user.toLocal8Bit().constData(),
pass.isNull() ? static_cast<const char *>(0) : pass.toLocal8Bit().constData(),
dbName.isNull() ? static_cast<const char *>(0) : dbName.toLocal8Bit().constData(),
0,
0,
0);
bool currentlyConnected = (result != 0);
In the above example, host, user, pass, and dbName are QString instances containing the connection information. Note that you need the MySQL development headers.