Quantcast
Channel: MySQL Forums - Connector/C++
Viewing all 527 articles
Browse latest View live

C++ Project (1 reply)

$
0
0
Which is the best topic for my project and easy to implemented?

C++ Basics (1 reply)

$
0
0
What is the main role of #include in C programing?Explain!

C API Support for calling mysql stored procedure - Not working in case of string argument (1 reply)

$
0
0
Below code works fine in case of integer argument like CREATE PROCEDURE p1(IN p_in INT)but not for varchar arguments.
varchar input parameter type is MYSQL_TYPE_STRING and output parameter type is MYSQL_TYPE_VAR_STRING
Problem: Getting empty result. As far my analysis, status = mysql_stmt_fetch(stmt); function returns 100(MYSQL_NO_DATA) though the entry present in the table.
NOTE: I tried calling the procedure manually into mysql like call p1('6666600222'); which results
mysql> call p1('6666600222');
+----------+
| password |
+----------+
| 1234 |
+----------+
1 row in set (0.00 sec)
Anyone help me to short out this?



I'm in the phase of developing a C project which interacts with mysql. So i planned to use mysql stored procedure and found a sample program in this link I just changed the program according to the requirements of my project. Here is the table structure

id | int(10) unsigned | NO | PRI | NULL | auto_increment |
username | varchar(64) | NO | MUL | NULL | |
password | varchar(25) | NO | | NULL | |


int main()
{
MYSQL_RES *result;
MYSQL *mysql=mysql_init(NULL);

/* connect to server with the CLIENT_MULTI_STATEMENTS option */
if (mysql_real_connect (mysql, "localhost", "root", "root123","DONT_USE", 0, NULL , CLIENT_MULTI_STATEMENTS) == NULL)
{
printf("mysql_real_connect() failed\n");
mysql_close(mysql);
}


MYSQL_STMT *stmt;
MYSQL_BIND ps_params[1]; /* input parameter buffers */
long int int_data[3]; /* input/output values */
my_bool is_null[3]; /* output value nullability */
int status;
char own_buf[25],input_buf[64];
memset(own_buf, 0, 25);
memset(input_buf, 0, 64);

/* set up stored procedure */
status = mysql_query(mysql, "DROP PROCEDURE IF EXISTS p1");
test_error(mysql, status);

status = mysql_query(mysql,
"CREATE PROCEDURE p1("
" IN p_in VARCHAR(64)) "
"BEGIN "
" SELECT password from data where username=p_in; "
"END");
test_error(mysql, status);

/* initialize and prepare CALL statement with parameter placeholders */
stmt = mysql_stmt_init(mysql);
if (!stmt)
{
printf("Could not initialize statement\n");
}
status = mysql_stmt_prepare(stmt, "CALL p1(?)", 10);
test_stmt_error(stmt, status);

/* initialize parameters: p_in, p_out, p_inout (all INT) */
memset(ps_params, 0, sizeof (ps_params));

ps_params[0].buffer_type = MYSQL_TYPE_STRING;
ps_params[0].buffer = (void *) &input_buf;
ps_params[0].buffer_length = sizeof(input_buf);
ps_params[0].is_null = 0;

/* bind parameters */
status = mysql_stmt_bind_param(stmt, ps_params);
test_stmt_error(stmt, status);

/* assign values to parameters and execute statement */
int_data[0]= 2; /* p_in */
int_data[1]= 20; /* p_out */

strcpy(input_buf,"'6666600222'");
int_data[0] = strlen(input_buf);
input_buf[int_data[0]] = '\0';
ps_params[0].length = &int_data[0];


status = mysql_stmt_execute(stmt);
test_stmt_error(stmt, status);

/* process results until there are no more */
do {
int i;
int num_fields; /* number of columns in result */
MYSQL_FIELD *fields; /* for result set metadata */
MYSQL_BIND *rs_bind; /* for output buffers */

/* the column count is > 0 if there is a result set */
/* 0 if the result is only the final status packet */
num_fields = mysql_stmt_field_count(stmt);

if (num_fields > 0)
{
/* there is a result set to fetch */
printf("Number of columns in result: %d\n", (int) num_fields);

/* what kind of result set is this? */
printf("Data: ");
if(mysql->server_status & SERVER_PS_OUT_PARAMS)
printf("this result set contains OUT/INOUT parameters\n");
else
printf("this result set is produced by the procedure\n");

MYSQL_RES *rs_metadata = mysql_stmt_result_metadata(stmt);
test_stmt_error(stmt, rs_metadata == NULL);

fields = mysql_fetch_fields(rs_metadata);

rs_bind = (MYSQL_BIND *) malloc(sizeof (MYSQL_BIND) * num_fields);
if (!rs_bind)
{
printf("Cannot allocate output buffers\n");
}
memset(rs_bind, 0, sizeof (MYSQL_BIND) * num_fields);

/* set up and bind result set output buffers */
for (i = 0; i < num_fields; ++i)
{
rs_bind.buffer_type = fields.type;
rs_bind.is_null = &is_null;

switch (fields.type)
{
case MYSQL_TYPE_LONG:
rs_bind.buffer = (char *) &(int_data);
rs_bind.buffer_length = sizeof (int_data);
break;
case MYSQL_TYPE_VAR_STRING:
rs_bind.buffer = (char *) own_buf;
rs_bind.buffer_length = sizeof(own_buf);
rs_bind.length = &int_data[1];
break;

default:
fprintf(stderr, "ERROR: unexpected type: %d.\n", fields.type);
}
}

status = mysql_stmt_bind_result(stmt, rs_bind);
test_stmt_error(stmt, status);

/* fetch and display result set rows */
while (1)
{
status = mysql_stmt_fetch(stmt);

if (status == 1 || status == MYSQL_NO_DATA)
break;

for (i = 0; i < num_fields; ++i)
{
switch (rs_bind.buffer_type)
{
case MYSQL_TYPE_LONG:
if (*rs_bind.is_null)
printf(" val[%d] = NULL;", i);
else
printf(" val[%d] = %ld;",
i, (long) *((int *) rs_bind.buffer));
break;
case MYSQL_TYPE_VAR_STRING:
printf(" val[%d] = %s;",i,(char*)rs_bind.buffer);
break;

default:
printf(" unexpected type (%d)\n",
rs_bind.buffer_type);
}
}
printf("\n");
}

mysql_free_result(rs_metadata); /* free metadata */
free(rs_bind); /* free output buffers */
}
else
{
/* no columns = final status packet */
printf("End of procedure output\n");
}

/* more results? -1 = no, >0 = error, 0 = yes (keep looking) */
status = mysql_stmt_next_result(stmt);
if (status > 0)
test_stmt_error(stmt, status);
} while (status == 0);

mysql_stmt_close(stmt);
}

OUTPUT:
Number of columns in result: 1
Data: this result set is produced by the procedure
End of procedure output

Mysql c++ application help (2 replies)

$
0
0
I was wondering if anyone can help me figure how to do something. I have created an C++ application with a menu that links to mySql database to pull data from. I have managed to pull data from my program to display it in c++ but the output formatting is total messed up. I have tried to make it look nice but my data doesn't seem to line up correctly.

So I was wondering if someone could tell me how to fix my formatting issue?

Another question is how to add data into mySQL database because one of the options is to add some data into a field. I have checked this online but can't seem to find exactly how to do this.

My query for option 2 and 3 don't seem to work, can you help me fix them?

My C++ program:

#include <stdio.h>
#include <mysql.h>
#include <iostream>
#include <iomanip>
using namespace std;
#define SERVER "students"
#define USER "********"
#define PASSWORD "*********"
#define DATABASE "cs566402"

int main() {

MYSQL *connect, mysql; //Creates a pointer to the MySQL instance
connect = mysql_init(&mysql); // Initialize the instance
connect = mysql_real_connect(connect, SERVER, USER, PASSWORD, DATABASE, 0, NULL, 0); //Connect to the specific database
if (connect) {
cout << "connection Succeeded\n";
} else {
cout << "connection failed\n";
}
MYSQL_RES *res_set;
MYSQL_ROW row;

cout << endl;
int option;
do {
cout << "1) List all wines that any winery produces " << endl;
cout << "2) List all wineries in a particular region " << endl;
cout << "3) List all wines with all of the grape varieties included in each wine" << endl;
cout << "4) Add a new winery (when adding a winery
there is no need for it to have any wines associated, but you must be able to put it in an existing
region)" << endl;
cout << "5) Exit Program " << endl;
cout << endl;
//Prompting user to enter an option according to menu
cout << "Please select an option : ";
cout << endl;
cin >> option; // taking option value as input and saving in variable "option"

if (option == 1) // Checking if user selected option 1
{
mysql_query(connect, "select w.WineId, w.WineName, wn.WineryName from Wine w, Winery wn where w.WineryId = wn.WineryId");
unsigned int i = 0;
res_set = mysql_store_result(connect);
unsigned int numrows = mysql_num_rows(res_set);

cout << setfill('-') << setw(1) << "+" << setw(11) << "-" << setw(1) << "+" << setw(45) << "-" << setw(1) << "+" << setw(30) << "-" << setw(1) << "+" << endl;
cout << setfill(' ') << setw(31) << left << "WineId" << setw(33) << left << "WineName" << setw(24) << left << "WineryName" << endl;
cout << setfill('-') << setw(1) << "+" << setw(11) << "-" << setw(1) << "+" << setw(45) << "-" << setw(1) << "+" << setw(30) << "-" << setw(1) << "+" << endl;

while (((row = mysql_fetch_row(res_set)) != NULL)) { //cout<<" %s\n",row !=NULL?row : "NULL";

cout << setw(1) << left << row << " \t \t" << setw(31) << row[i + 1] << " \t \t" << setw(11) << right << row[i + 2] << endl;
}
} else if (option == 2) // Checking if user selected option 2
{
mysql_query(connect, "select WineryName, Region from Winery");
unsigned int i = 0;
res_set = mysql_store_result(connect);
unsigned int numrows = mysql_num_rows(res_set);
while (((row = mysql_fetch_row(res_set)) != NULL)) { //cout<<" %s\n",row !=NULL?row : "NULL";

cout << "|" << row << "| \t";
cout << row[i + 1] << endl;
}
} else if (option == 3) // Checking if user selected option 3
{
mysql_query(connect, "select g.GrapeType, w.WineName from GrapeType g, Wine w, Varieties v where g.GrapeId = v.GrapeId and v.WineId = w.WineId");
unsigned int i = 0;
res_set = mysql_store_result(connect);
unsigned int numrows = mysql_num_rows(res_set);
while (((row = mysql_fetch_row(res_set)) != NULL)) { //cout<<" %s\n",row !=NULL?row : "NULL";

cout << "|" << row << "| \t";
cout << row[i + 1] << endl;
}
} else if (option == 4) // Checking if user selected option 3
{

} else if (option == 5) // Checking if user selected option 4
{
cout << "Terminating Program" << endl;
} else //if user has entered invalid choice (other than 1,2,3,4, or 5)
{
//Displaying error message
cout << "Invalid Option entered" << endl;
}
} while (option != 5); //condition of do-while loop

//return 0;



mysql_close(connect);
return 0;
}

Segmentation fault when inserting a large string (no replies)

$
0
0
I have a repeatable segmentation fault when using prepared statements with large chunks of data bound to a mediumblob data type. I’ve searched the outstanding bugs, but can’t find anything relevant, and just wanted to sanity check what I’m doing, before I go ahead and create a new bug.

My code is well established and has been working in a variety of iterations for years, but I noticed recently that one subroutine that loads files into a database was failing on a new example, which was larger than prior files.

The code is fully unit tested, and larger read and writes are working as expected within the tests.

When I looked at the failing section, the parameter had been bound to a std::string using setString, rather than a stream and setBlob. In all cases, the segmentation fault was triggered when execute was issued.

Off the back of this, I added additional tests and the results I found were:

setString fails at ~250k with a segmentation fault
getString, setBlob and getBlob all work fine, and appear only limited by max_allowed_packet

I’m a bit of an anal coder, and the compiler generates no warnings, plus a valgrind run with a smaller file generates no errors at all.

With a large file, the segmentation fault is generated, and valgrind reports (heavily abridged):
Conditional jump or move depends on uninitialised value(s)
Uninitialised value was created by a stack allocation
sql::mysql::MySQL_Prepared_Statement::execute() (in /usr/lib/libmysqlcppconn.so.7.1.1.3)

Which looks like the library code has tried to allocate the string on the stack, failed, but has not checked the return before using it.

Code versions:
libmysqlcppconn.so.7.1.1.3
libmysqlclient.so.18.1.0

i got the below errors while executing the visual studio c++ console application (3 replies)

$
0
0
i have written the code in visual studio c++ in console application in that i am trying to connect to mysql database but i am getting the following errors

1) unresolved external symbol _mysql_close@4 referenced in function _main PDIconsole

2)unresolved external symbol _mysql_error@4 referenced in function _main PDIconsole

3)unresolved external symbol _mysql_free_result@4 referenced in function _main PDIconsole

4)unresolved external symbol _mysql_fetch_row@4 referenced in function _main

5)unresolved external symbol _mysql_init@4 referenced in function _main PDIconsole
6)unresolved external symbol _mysql_query@8 referenced in function _main PDIconsole

7)unresolved external symbol _mysql_real_connect@32 referenced in function _main PDIconsole

8)unresolved external symbol _mysql_use_result@4 referenced in function _main PDIconsole

MySql C++ connector - conn->commit() doesn't throw exception (1 reply)

$
0
0
Hi,
sql::Connection *conn
I observed that conn->commit() doesn't throw exception if client loses connection to mysql server just before executing this commit statement.

As no exception is thrown client gets a wrong impression that the transaction was committed whereas actually it was not!

Is this a MYSQL C++ connector bug ?

Regards,
Akshay

how to escape strings in mysqlcppconn (no replies)

$
0
0
Hello,
i wrote a C++ program and using the mysqlcppconn library.
Now i would love to escape sql special characters for make it more stable and save.
I don't know how to do with that API. Of course i just can use the C api.
But before i mix APIs i would like to ask if there is somebody who knows how to escape these chars with mysqlcppconn.

Regards
FK

std::bad_alloc thrown on attemt to setSchema (1 reply)

$
0
0
Hi -- I have this really simple code:

auto mysql_driver = get_driver_instance();
sql::Connection *c = mysql_driver->connect("172.17.0.1", "root", "tooth");
c->setSchema("mysql");
delete c;

That is generating this error:

terminate called after throwing an instance of 'std::bad_alloc'
what(): std::bad_alloc
Aborted

The following command however works in the terminal:
$ mysql -h 172.17.0.1 -u root -ptooth mysql

If I comment out the line with the call to setSchema() in it, no error is thrown, so it looks like the first attempt to (presumably lazy-) use the connection is causing the error.

I'm on linux, and installed Connector/C++ from the tar file.

Could anybody please advise me on what is going wrong, here? I've been trying to fix this for hours, now, but to no avail.
Thanks in advance for any & all assistance,
Doug.

Error trying to connect to MySQL with Eclipse (no replies)

$
0
0
Hello,

I am trying to connect to the MySQL Database using Eclipse for C++.

I have added the dynamic library mysqlcppconn.lib and also have the relevant dll files in my executable folder

I get the exact error
"
relocation truncated to fit: R_X86_64_32 against symbol `__imp_get_driver_instance' defined in .idata$5 section in C:\Program Files\MySQL\Connector.C++1.1\lib\opt\static/mysqlcppconn.lib(mysqlcppconn.dll.b) "


i have already tried adding -fPIC and -mcmodel=medium/large to compiler
and _mcmodel=medium/large and -dynamic to the linker.
Didnt have any success with these


Any help as to how can i resolve this error?

SQLException by PreparedStatement::getMoreResults in example C++ code (1 reply)

$
0
0
Hi all,

I got the following exception when running the example code here:
http://dev.mysql.com/doc/connector-cpp/en/connector-cpp-tutorials-stored-routines-prepared-statement-with-result.html

# ERR: SQLException in sp_scenario3.cpp(main) on line 70
# ERR: MySQL_Prepared_Statement::getMoreResults (MySQL error code: 0, SQLState: )


Here is the output generated by the example code:
Connector/C++ tutorial framework...

Name: Cocos (Keeling) Islands Population: 600
Name: Christmas Island Population: 2500
Name: Norfolk Island Population: 2000
Name: Niue Population: 2000
Name: Pitcairn Population: 50
Name: Tokelau Population: 2000
Name: United States Minor Outlying Islands Population: 0
# ERR: SQLException in sp_scenario3.cpp(main) on line 70
# ERR: MySQL_Prepared_Statement::getMoreResults (MySQL error code: 0, SQLState: )

It seems that the error was generated by calling pstmt->getMoreResults() in the if condition.

I'm running the packages on Ubuntu 14.04 LTS and the version of mysql connector/c++ is 1.0.2 according to Software Center. I'd really appreciate it if anyone could help!

How do I set the LOCAL INFILE option (for load data file command) using setClientOption (no replies)

$
0
0
I am writing a C++ function using the C++ connector library that will take a table name and data file name and will use
the LOAD DATA command to bulk load the data from the file. How can i set the LOCAL_INFILE parameter for the connection to true.

Exit clean up when use "sql::Connection" after network disabled. (1 reply)

$
0
0
Hello ^^

I'm new on using mysql_cpp_conn with c++ and having a problem.


below is my testing code,
-----------------------------------------------

sql::Connection * _con;
sql::Statement * _stmt;

...


try {
if (false == _con->isValid()){ // ----------- A
return false;
}
_pstmt = _con->prepareStatement(string); // ------------ B
}catch (sql::SQLException &e) {
manageException(e); // ------------ C
return false;
}
-----------------------------------------------
this works well in normal situation. but in my testing scenarios this code
exit clean up. no throwing exceptions.


[ my scenario ]

1. procses start~

2. breaking points at code [A, b, C]

3. run code [A] -> it's ok

3. disable ethernet adaptor! it's simulation for ethernet-adaptor's hardware faults.

4. run code B -> exit clean up. process terminated. no exceptions.

* in case unpluged rj45 cable, it's throw SQLException. but in case disabled ethernet adaptor, it's just exit process.


it's ok function's failed but i want to keep running my process not exit.

THX

Ineffective Prepared Delete Statement (no replies)

$
0
0
I'm attempting to execute a prepared delete statement like so:

prep_stmt = conn->prepareStatement("DELETE FROM my_table WHERE my_column = ?");

sql::SQLString test_string = "\'asdf\'";

prep_stmt->setString(1, test_string);

int update_count = prep_stmt->executeUpdate();

There appears to be no runtime errors (at least, no exception is thrown). However, update_count is zero, and investigating the contents of the database after execution reveals that the associated data entry was not removed.

Has anyone seen this before?

C++ Connector / Json / Prepared Statements (1 reply)

$
0
0
For a JSON datatype which 'set' method should I use?

for a string ...

prep_statement->setString(2, pseudojson);

mysqlcppconn.dll RUNTIME advice and help (2 replies)

$
0
0
Hi to all,

I would like to know
1. if it is possible to use mysql connector for c++ without the need of the
mysqlcppconn.dll to be external (if it can be embed inside my executable c++ app and stay embed inside it while running)
2. if 1 can`t be possible at least can this mysqlcppconn.dll be embed inside my app and when my application starts exports the mysqlcppconn.dll to a folder so it can be used by mysql connector c++ inside my app and then when my application closes delete this mysqlcppconn.dll file ?

Can anyone give me a clear answer i would at least like to have one of this options for my c++ win32 app executable with the use of mysql c++ connector

Unresolved Externals (1 reply)

$
0
0
Hello i have a problem with this mysql c++ connector i setup everything all includes and libraries and is still gives me an errors :
What have i done so far :

Additional Include Directories : ...MySQL\MySQL Connector C++ 1.1.7\include

Also have boost installed because it was missing :MySQL\MySQL Connector C++ 1.1.7\include\boost

Additional Library Directories :MySQL\MySQL Connector C++ 1.1.7\lib\opt
There was missing some libraries but i got them from Mysql server that i download from mysql.com

Additional Dependencies: mysqlcppconn-static.lib and libmysql.lib
i havent done last step width CPPCONN_PUBLIC_FUNC= because once i do that i got like 300 errors

my code looks like this :
sql::mysql::MySQL_Driver* driver;
sql::Connection* con;

driver = sql::mysql::get_mysql_driver_instance();
con = driver->connect(cfg->GetDatabase()->host, cfg->GetDatabase()->username, cfg->GetDatabase()->password);

delete con;

build 2.0.3 source on minGW64 fails (1 reply)

$
0
0
Hello,
I am trying to build Connector/C++ 2.0.3 source on windows10 64bit with mingw64 6.2.0 installed (x86_64-6.2.0-posix-seh-rt_v5-rev1).
cmake configuration runs fine. However, I got below errors and do not know how to proceed. Would you please help me? Thanks a lot.

C:\mysql-connector-cpp-2.0>cmake --build . --config Debug
cdk/mysqlx/CMakeFiles/cdk_mysqlx.dir/flags.make:6: *** missing separator. Stop.
CMakeFiles\Makefile2:717: recipe for target 'cdk/mysqlx/CMakeFiles/cdk_mysqlx.dir/all' failed
mingw32-make.exe[1]: *** [cdk/mysqlx/CMakeFiles/cdk_mysqlx.dir/all] Error 2
Makefile:126: recipe for target 'all' failed
mingw32-make.exe: *** [all] Error 2

mixing mingw64 gcc and prebuilt vs14 2.0.3 library (2 replies)

$
0
0
Hello,
I try to compile the example given by

using ming64 6.2.0 on windows10 64bit machine. I use the prebuilt vs14 2.0.3 library. None of the connector API implementations can be found whether I use static or dynamic mysqlcppconn2. Do I have to build the connector from source using mingw64 gcc/g++ before I can use it? Any missing steps? Thank you very much.

g++.exe -w -std=c++11 -m64 -g -fexceptions -I"C:\Program Files\MySQL\mysql-connector-c++-2.0.3-windows-x86-64bit\include" -c C:\Users\lampa\Documents\RFID\readRFID\main.cpp -o obj\Debug\main.o
g++.exe -L"C:\Program Files\MySQL\mysql-connector-c++-2.0.3-windows-x86-64bit\lib64\vs14" -o bin\Debug\readRFID.exe obj\Debug\main.o -m64 -lmysqlcppconn2 -lpthread
obj\Debug\main.o: In function `main':
C:/Users/lampa/Documents/RFID/readRFID/main.cpp:43: undefined reference to `mysqlx::internal::XSession_base::getSchema(mysqlx::string const&, bool)'
C:/Users/lampa/Documents/RFID/readRFID/main.cpp:44: undefined reference to `mysqlx::Schema::createCollection(mysqlx::string const&, bool)'
C:/Users/lampa/Documents/RFID/readRFID/main.cpp:50: undefined reference to `mysqlx::Result::getDocumentId() const'

Connector/C++ fror OSX (1 reply)

$
0
0
Hi, ALL,
On the download page for MySQL Connector/C++ for OSX it is said that it is compatible with 10.12, 10.11 and 10.10 for the latest version.

There is also a link on that page which says: "Looking for previous GA version?" When clicking on that link you will be able to download the versions for 10.4 and 10.5.

I'm curious - where can I download the version for 10.6 - 10.9?
And also out of curiosity - who decides when to stop supporting the OSX version?

Thank you.

P.S.: If someone has a version of the connector which can be installed on OSX 10.8, I will appreciate the link to download. Hopefully Oracle will not punish you - I'm not asking for an actual DBMS, just for the library that I can use to access it from my software. I just hate when the company does not support something that is still on the market...
Viewing all 527 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>