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!
Related
I am having problems using the sqlite3 C/C++ amalgamation within the context of Unreal Engine 4...
I can open a connection to the database write data to it, verifying this using DB Browser, but running SELECT statements using sqlite3_prepare_v2 and sqlite3_step is giving unexpected behaviours. I'm checking the return values and not seeing any error codes, but I am seeing a SQLITE_DONE when I'd expect to see SQLITE_ROW returned by sqlite3_step. If I log out the result of sqlite3_expanded_sql, I get the expected statement with all parameters properly inserted and if I copy & paste this into DB Browser, I get the expected results.
The data being pulled is specific to each run of the program so I know that I'm not seeing old or irrelevant data in DB Browser, and I know that my "write" functions are also operating as expected.
What's particularly strange is that after commenting out all references to SQLPreparedStatementString (which I was using in an attempt to debug the issue) the code performs differently: I do now get one row back (instead of the expected 4).
This almost makes me suspect that there's a memory issue going on, perhaps sqlite3 and Unreal are both writing to the same sections of memory without communicating that to each other? I tend to rely on UE4's memory management and don't have a lot of C/C++ experience outside of UE4, so my knowledge of things like malloc is limited pretty much just to the general feeling that "here be dragons" etc. I also understand that sqlite3_prepare_v2 and sqlite3_step are functions that tend to do a lot of memory allocation, but if that's what's causing the problem, I'm surprised that it's only occuring so rarely, since I'm successfully calling them several thousand times (to add data) on each game run.
I understand that it's possible to set compile-time options for sqlite that pre-allocate it a memory block so that it doesn't use malloc at all during runtime, but I've not quite worked out how to do that in the context of including the amalgamation in UE4 just yet.
Relevant code below:
TArray<FName> UOzyBrainLogger::GetLoggedCivsForTurn(const int32 TurnNumber)
{
TArray<FName> rVal;
sqlite3_stmt *SQLStatement;
FString SQLCommand = "SELECT DISTINCT CivName FROM Decision WHERE (GameID = ? AND TurnNumber = ?) ;";
int rc;
rc = sqlite3_prepare_v2(DB, TCHAR_TO_UTF8(*SQLCommand), -1, &SQLStatement, NULL);
if (rc == SQLITE_OK)
{
//FString SQLPreparedStatementString;
UE_LOG(OzyBrainLogger, Log, TEXT("Getting Civs logged for turn %d in game %s"), TurnNumber, *GameID);
if(sqlite3_bind_text( SQLStatement, 1, TCHAR_TO_UTF8(*GameID), -1, SQLITE_STATIC) == SQLITE_OK &&
sqlite3_bind_int( SQLStatement, 2, TurnNumber) == SQLITE_OK)
{
//SQLPreparedStatementString = UTF8_TO_TCHAR(sqlite3_expanded_sql(SQLStatement));
//UE_LOG(OzyBrainLogger, Log, TEXT("Successfully created statement: %s"), *SQLPreparedStatementString);
rc = sqlite3_step(SQLStatement);
if (rc == SQLITE_DONE)
{
UE_LOG(OzyBrainLogger, Log, TEXT("No results found?"));
}
else if (rc != SQLITE_ROW)
{
UE_LOG(OzyBrainLogger, Log, TEXT("Return code was: %d"), rc);
}
while (rc == SQLITE_ROW)
{
FName CivName = FName(*FString(UTF8_TO_TCHAR((const char*) sqlite3_column_text(SQLStatement, 0))));
//UE_LOG(OzyBrainLogger, Log, TEXT("Returning %s for turn %d via statement: %s"), *CivName.ToString(), TurnNumber, *SQLPreparedStatementString);
UE_LOG(OzyBrainLogger, Log, TEXT("Returning %s for turn %d"), *CivName.ToString(), TurnNumber);
rVal.Add(CivName);
rc = sqlite3_step(SQLStatement);
}
}
else
{
UE_LOG(OzyBrainLogger, Warning, TEXT("%s"), UTF8_TO_TCHAR(sqlite3_errmsg(DB)));
}
}
else
{
UE_LOG(OzyBrainLogger, Warning, TEXT("%s"), UTF8_TO_TCHAR(sqlite3_errmsg(DB)));
}
sqlite3_finalize(SQLStatement);
return rVal;
}
I might be missing something really obvious, but I'm not sure how to investigate this further to make progress so any advice on avenues to explore would be very helpful.
Am feeling a bit lost!
I think I managed to fix it! The problem seems to have been a combination of:
Calling sqlite3_open in my object's constructor expecting singleton-like behaviour when UE4 calls constructors silently from time to time (e.g. on compile).
Using SQLITE_STATIC in place of SQLITE_TRANSIENT
Adding return code (rc) checking absolutely everywhere
Fixing both of these issues seems to have resolved the main problem.
The final issue (getting only 2 rows back instead of 4) was a more pedestrian rookie error (I'd rearranged the call to sqlite3_step into a do ... while loop and accidentally ended up calling sqlite3_step twice per iteration!
The things that didn't fix the main issue included calling sqlite3_config with SQLITE_CONFIG_MEMSTATUS, SQLITE_CONFIG_LOOKASIDE and SQLITE_CONFIG_HEAP, however: when I started checking the return codes for these calls properly and finding errors, that was a major clue to realising that something had already started the database connection without me realising it (i.e. UE4's silent constructor-calling on compile)
I am using following simple code to connect to database and I am getting error as ORA-24399 which says invalid number of connections specified. I have googled enough but not clue. This is a CPP program.
Following is code Snippet:
try
{
Environment *env = Environment::createEnvironment(Environment::DEFAULT);
Connection *con= env->createConnection("test","test","testdb");
}
catch(SQLException ex)
{
cout<<ex.getMessage().c_str();
}
P.S Using SQL Plus I am able to connect to the database where this code is being run. There are no issues there. Only through program there is a failure seen.
P.P.S Tried using connectionpool as well but still no luck...
Looking at your error, it seems that the problem is somewhere else in your code: you should fix the parameters (related to connection numbers) in the call to OCIConnectionPoolCreate.
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 ).
I am helping a friend with his bachelor thesis project. It is a program that calculates bending moments for various materials. One of the extra requirements that the client desires is database functionality to store and retrieve various pieces of data being used in the program.
The program is a forms application written in managed C++. I jumped on board to help with writing the database functionality. I am using MySQL Server 5.5 and the MySQL Connector/C++ to bridge the program and the database. Everything has been going pretty well and all the functionality we need works just fine, but only in debug. As soon as we put the program into release mode there is undefined behavior occurring at runtime. Below is the function that is used to open a connection to the database:
try
{
m_driver = get_driver_instance();
m_conn = m_driver->connect(m_dbHost, m_dbUser, m_dbPwd);
m_conn->setSchema(m_dbSchema);
}
catch(sql::SQLException &e)
{
int a = e.getErrorCode();
MessageBoxA(NULL, e.what(), "DB Error", MB_OK);
}
The values passed into the connect function are all std::string. In debug mode the connection is made with no issues. In release mode an exception is caught after the connect function is called, and displays the message "Unknown MySQL Server Host '####' (0)" where the #### is always some garbage text. I also notice that in the output window another exception is being thrown, this one is the type System.Runtime.InteropServices.SEHException.
I have been doing some research and have seen numerous cases of this exception on many forums (and here on stack exchange) but no one seems to be having this issue with the MySQL connector. My assumption is that the memory is being corrupted because the program is mixed mode, with the main program code being written in Managed C++ and my database helper code being in native C++ (as required by the connector).
Is there something I can change in my code to try and fix this issue to that the strings aren't being corrupted at run time. I have tried many different hacks to try and solve the problem but nothing has worked.
Thanks,
Tom
Update: I am now seeing this error in debug mode. I added code to retrieve values from the database and populate some text boxes on the form. The code is as follows:
// Populate the form with material details
String^ selectedMaterial = (String^)(comboBox1->SelectedItem);
string selectedMaterial_ = "";
MarshalString(selectedMaterial, selectedMaterial_);
sql::ResultSet* results = dbHelper.GetData("matname", selectedMaterial_);
if (results->rowsCount() == 1)
{
// Outdim
string outdim_ = "";
outdim_ = results->getString("outdim");
String^ outdim = gcnew String(outdim_.c_str());
textBox1->Text = outdim;
}
else
{
// !!!! Duplicate materials in list
}
When it tries to read outdim from the result set the SEHException is thrown, and the only other piece of information given is that it was thrown in an external component.
Update 2: I ran Application Verifier against the debug executable and then launched the program from VS2010. However the form window never loads so somewhere along the line the program must be getting halted. Strangely there is absolutely no information in the log files in Application Verifier. I also tried with the release version and I didnt get any useful information from that either.
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.