Error detection in C client program connecting MySQL - mysql

My C client program connects with MySQL server. I can connect, but the problem arises when I try to implement error detection codes. If I do the following (here I have intentionally put incorrect user name):
#include "mysql.h"
int main()
{
MYSQL* conn_ptr_db;
conn_ptr_db = mysql_init(NULL);
if(!conn_ptr_db)
{
perror("Error connecting to MySQL! ");
exit(0);
}
if(mysql_real_connect(conn_ptr_db,"localhost","rooti","root","mysql",0,NULL,0))
{
printf("Hurrah! we have connected to MySQL! ");
mysql_close(conn_ptr_db);
}
else
{
printf("Connection failed to MySQL! \n");
printf("Error code: %d %s %s\n",mysql_errno(conn_ptr_db),mysql_sqlstate(conn_ptr_db),mysql_error(conn_ptr_db));
}
//mysql_close(conn_ptr_db);
return 0;
}
Now the output to this program:
./db_access
Connection failed to MySQL!
Error code: 1045 28000 Access denied for user 'rooti'#'localhost' (using password: YES)
This is the correct output.
But if I do the following:
#include "mysql.h"
int main()
{
MYSQL* conn_ptr_db;
conn_ptr_db = mysql_init(NULL);
if(!conn_ptr_db)
{
perror("Error connecting to MySQL! ");
exit(0);
}
//CHANGES -------------
conn_ptr_db = mysql_real_connect(conn_ptr_db,"localhost","rooti","root","mysql",0,NULL,0);
if(conn_ptr_db)
{
printf("Hurrah! we have connected to MySQL! ");
mysql_close(conn_ptr_db);
}
else
{
printf("Connection failed to MySQL! \n");
printf("Error code: %d %s %s\n",mysql_errno(conn_ptr_db),mysql_sqlstate(conn_ptr_db),mysql_error(conn_ptr_db));
}
//mysql_close(conn_ptr_db);
return 0;
}
I get the following output:
./db_access
Connection failed to MySQL!
Error code: 0 08001
Here, the mysql_errno() and mysql_error() are not working. Why?

After the connection has failed conn_ptr_db is set to NULL. You then try and use this value as a paramter to a call to msql_errono(), in effect msql_errno(NULL). Hence the error code your getting.

Because in the second example you assign the result to conn_ptr_db.
You should not have done so.
From the documentation:
A MYSQL* connection handle if the
connection was successful, NULL if the
connection was unsuccessful. For a
successful connection, the return
value is the same as the value of the
first parameter.
In the case of an unsuccessful connection (which you have), you've replaced your conn_ptr_db object with NULL then attempt to do stuff with it (mysql_error).
The documentation for mysql_error doesn't explicitly say that a NULL parameter is disallowed, but it's clear that you won't get the error relating to the original, actual connection context that you overwrote.

Related

error while connecting mariadb with c : undefined reference to `mysql_init#4'

I am trying to connect to mariadb database using c program. Initially it was showing error for #include <mysql.h> as no such file or directory.
But after including directory name, that problem is solved now, but it is showing another error.
Following is the code I was trying to run:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// #include "C:/Program Files/MariaDB 10.11/include/mysql/my_global.h"
#include "mysql/mysql.h"
int main (int argc, char* argv[])
{
// Initialize Connection
MYSQL *conn;
if (!(conn = mysql_init(0)))
{
fprintf(stderr, "unable to initialize connection struct\n");
exit(1);
}
// Connect to the database
if (!mysql_real_connect(
conn, // Connection
"mariadb.example.net", // Host
"db_user", // User account
"db_user_password", // User password
"test", // Default database
3306, // Port number
NULL, // Path to socket file
0 // Additional options
));
{
// Report the failed-connection error & close the handle
fprintf(stderr, "Error connecting to Server: %s\n", mysql_error(conn));
mysql_close(conn);
exit(1);
}
// Use the Connection
// ...
// Close the Connection
mysql_close(conn);
return 0;
}
I am getting following error in output:
PS C:\Dev\Win> gcc Db_con.c -o Db_con
C:\Users\hajos\AppData\Local\Temp\ccGZ2Rhz.o:Db_con.c:(.text+0x1e): undefined reference to `mysql_init#4'
C:\Users\hajos\AppData\Local\Temp\ccGZ2Rhz.o:Db_con.c:(.text+0xa1): undefined reference to `mysql_real_connect#32'
C:\Users\hajos\AppData\Local\Temp\ccGZ2Rhz.o:Db_con.c:(.text+0xaf): undefined reference to `mysql_error#4'
C:\Users\hajos\AppData\Local\Temp\ccGZ2Rhz.o:Db_con.c:(.text+0xd9): undefined reference to `mysql_close#4'
collect2.exe: error: ld returned 1 exit status
Can anyone explain what is the problem and how to solve it?
You have to link against the MariaDB Connector/C libraries.
From MariaDB Connector/C documentation:
Linking your application against MariaDB Connector/C
Windows
For static linking the library libmariadb.lib is required, for dynamic linking use libmariadb.dll. Using the MSI installer, these libraries can be found in the lib directory of your MariaDB Connector/C installation.
Unless you use the experimental plugin remote_io (which requires the curl library) there are no dependencies to other libraries than the Windows system libraries.

exception when using boost::serialization with boost::asio

my server runs following code:
boost::asio::streambuf streambuf;
std::istream istream(&streambuf);
boost::archive::xml_iarchive xml_iarchive(istream);
boost::asio::read_until(socket_, streambuf, '\n');
When the server is up and running I connect vie telnet from another machine. Immediately after connection is established, the connection is getting closed and the server crashes with following exception:
terminate called after throwing an instance of 'boost::archive::xml_archive_exception'
what(): unrecognized XML syntax
Where is the failure at the code snippet above? It looks to me that the telnet session is sending a '\n' before I manually enter some XML string.
You didn't post a sscce, so I created one for you
#include <boost/asio.hpp>
#include <boost/archive/xml_iarchive.hpp>
int
main()
{
try {
boost::asio::streambuf streambuf;
std::istream istream(&streambuf);
boost::archive::xml_iarchive xml_iarchive(istream);
} catch ( const std::exception& e ) {
std::cerr << e.what() << std::endl;
}
}
As expected, an exception is throw from line 10:
samm$ ./a.out
unrecognized XML syntax
This has nothing to do with Boost.Asio, you're trying to deserialize an empty buffer, which isn't valid XML. To solve this, delay the deserialization until after reading from the socket into the buffer
boost::asio::read_until(socket_, streambuf, '\n');
std::istream istream(&streambuf);
boost::archive::xml_iarchive xml_iarchive(istream);

Why am I getting a segmentation fault (core dumped)?

This is the code I am trying to run. It compiles fine, and worked great until yesterday.
#include <my_global.h>
#include <mysql.h>
int main(int argc, char **argv)
{
MYSQL *conn;
MYSQL_RES *result;
MYSQL_ROW row;
int num_fields;
int i;
conn = mysql_init(NULL);
mysql_real_connect(conn, "hostname", "username", "password", "database_name", 0, NULL, 0);
mysql_query(conn, "SELECT * FROM tabletest");
result = mysql_store_result(conn);
num_fields = mysql_num_fields(result);
while ((row = mysql_fetch_row(result)))
{
for(i = 0; i < num_fields; i++)
{
printf("%s ", row[i] ? row[i] : "NULL");
}
printf("\n");
}
mysql_free_result(result);
mysql_close(conn);
}
Note that the parameters for mysql_real_connect() are generic here for privacy, but like I said, it worked yesterday. When I try to run the code after compiling successfully, I get:
Segmentation fault (core dumped)
Paddy pointed out the key problem, I didn't error check. After error checking, I found out that I wasn't being granted access to my remote server and was getting
Error 1045: Access denied for user 'username'#'ip' (using password: YES)
I then realized that the IP address of my computer changed after turning it on. I never knew this happened. So I had to go back into cPanel, and add my 'new' IP address to the remote access list for MySQL, and it works. Now the issue is to find out how my IP address can stay static.
The moral of the story is to always handle errors.

mysql_errno always returns 0

I am trying to connect to the server with a wrong user or password and as expected it fails but the mysql_errno always returns 0. is there something wrong with my mysql installation?.
EDIT: I am using a c program to connect.
int main(int argc, char *argv[]) {
MYSQL my_connection;
mysql_init(&my_connection);
if (mysql_real_connect(
&my_connection,
"localhost",
"rick",
"I do not know",
"foo", 0, NULL, 0)) {
printf("Connection success\n");
mysql_close(&my_connection);
} else {
fprintf(stderr, "Connection failed\n");
if (mysql_errno(&my_connection)) {
fprintf(stderr, "Connection error %d: %s\n",
mysql_errno(&my_connection), mysql_error(&my_connection));
}
}
return EXIT_SUCCESS;
}
IN the book the output is supposed to say error 1045:
In my case it is 0 and nothing but connection failed is printed.
mysql_errno() only reports errors from a valid connection.
The error number comes from the actual database. How can it retrieve these without a connection in the first place?
You'll notice in the API example, they don't bother with the error number for a failed connection
MYSQL mysql;
mysql_init(&mysql);
mysql_options(&mysql,MYSQL_READ_DEFAULT_GROUP,"your_prog_name");
if (!mysql_real_connect(&mysql,"host","user","passwd","database",0,NULL,0))
{
fprintf(stderr, "Failed to connect to database: Error: %s\n",
mysql_error(&mysql));
}

Dual connection to sql server in c code

I'm working on a project in C with MySQL
I'm having a problem connection to the MySQL server. First have one time a connection, this works.
But now in an other section an also need to retrieve info from the db
There I use the same code to connect.
conn = mysql_init(NULL);
//check if there is a connection
if (conn == NULL)
{
printf("Error %u: %s\n", mysql_errno(conn), mysql_error(conn));
exit(1);
}
if (mysql_real_connect(conn, "localhost", "test", "test", "test", 0, NULL, 0) == NULL)
{
printf("Error %u: %s\n", mysql_errno(conn), mysql_error(conn));
}
But when I use this a second time, I get an error
Unhandled exception at 0x009818c9 in
simple.exe: 0xC0000005: Access
violation reading location 0x00000000.
it crashes on the if(conn == NULL)
Anyone got an idea why this don't work?
That seems to be windows's version of a segmentation fault (I've never compiled anything on windows), so, check your pointers and make sure they aren't null, and if they are to be global, make sure they are on the heap.