Use mysql embedded and --local-infile=1 with c++? - c++

I am connecting to a mysql database using the embedding server (linking against mysqld) in c++. I have the following code:
static char *server_options[] = \
{ (char *)"mysql_test",
(char *)"--datadir=/home/cquiros/temp/mysql/db2",
(char *)"--default-storage-engine=MyISAM",
(char *)"--loose-innodb=0",
(char *)"--local-infile=1",
(char *)"--skip-grant-tables=1",
(char *)"--myisam-recover=FORCE",
(char *)"--key_buffer_size=16777216",
(char *)"--character-set-server=utf8",
(char *)"--collation-server=utf8_bin",
NULL };
int num_elements = (sizeof(server_options) / sizeof(char *)) - 1;
mysql_library_init(num_elements, server_options, NULL);
m_mysql = mysql_init(NULL);
char enable_load_infile = 1;
if (mysql_options(m_mysql,MYSQL_OPT_LOCAL_INFILE, (const char *)&(enable_load_infile)))
qDebug() << "Error setting option";
mysql_real_connect(m_mysql, NULL,NULL,NULL, "database1", 0,NULL,0);
The connection works and I can query and create tables however, when I try to execute "load data local infile ..." I always get "The used command is not allowed with this MySQL version" even though I am setting --local-infile=1 in the server options or setting it in code in:
char enable_load_infile = 1;
if (mysql_options(m_mysql,MYSQL_OPT_LOCAL_INFILE, (const char *)&(enable_load_infile)))
qDebug() << "Error setting option";
Any idea what I am doing wrong and how to fix it?
Many thanks for your help.
Carlos.

#QLands I realize its over a year since you've asked this question, but I figured I'd reply just for posterity in case others like me are googling for solutions.
I'm having the same issue, I can get LOAD DATA LOCAL INFILE statements to work from the Linux mysql CLI after I explicitly enabled it in the /etc/mysql/my.cfg file. However I CANNOT get it to work with the MySQL C++ connector -- I also get the error "The used command is not allowed with this MySQL version" when I try and run a LOAD DATA LOCAL INFILE command through the MySQL C++ connector. wtf right?
After much diligent googling and finding some back alley tech support posts I've come to conclude that the MySQL C++ connector did not (for whatever reason) decide to implement the ability for developers to be able to allow the local-infile=1 option. Apparently some people have been able to hack/fork the MySQL C++ connector to expose the functionality, but no one posted their source code -- only said it worked. Apparently there is a workaround in the MySQL C API after you initialize the connection you would use this:
mysql_options( &mysql, MYSQL_OPT_LOCAL_INFILE, 1 );
Here are some reference articles that lead me to this conclusion:
1.)
How can I get the native C API connection structure from MySQL Connector/C++?
2.)
Mysql 5.5 LOAD DATA INFILE Permissions
3.)
http://osdir.com/ml/db.mysql.c++/2004-04/msg00097.html
Essentially if you want the ability to use the LOAD DATA LOCAL INFILE functionality -- you have to use the mysql C API or execute it from the command line or hack/fork the existing mysql C++ api to expose the connection structure
:(

Related

SQLITE_CANTOPEN - windows c++

I am trying to create an Sqlite database in the selected folder but can`t do this.
Operating System - Windows, editor - Visual studio, progect encoding is unicode. Encoding of input string with database connection unknown. Language - C++
The problem:
I can't create database when I use following connection string: file:C:/Users/Public/Desktop/testDb.sqlite
I am always getting error 14 (SQLITE_CANTOPEN).
I use following function to create database:
CSqliteManager::CSqliteManager(const char* dbName)
{
db = nullptr;
int rc = sqlite3_open(dbName, &db);
if (rc != SQLITE_OK)
{
db = nullptr;
}
}
How should me change connection string to create database fo the sollowing pass:
C://Users/Public/Desctop/MyBD.sqlite
You can't use URI style filenames with sqlite3_open() as they're disabled by default (I'm assuming you didn't enable them globally). Instead you need to use sqlite3_open_v2() with the appropriate option (SQLITE_OPEN_URI). Details and more details.
(Or just not use a URI, of course)

Sample stored procedure execute from c++ program

DBPROCESS *dbconnect(DBPROCESS *dbproc)
int i,count;
char choice;
char num[2];
int page;
int index;
unsigned long num_recs = 0;
char db_epass[40], db_user[40], db_pass[40], db_database[60], db_server[40], db_dbname[60];
bool status,valid;
LOGINREC *loginrec;
int y=ScrWidth/2-10;
count=0;
/I WANT TO EXECUTE STORED PROCEDURE FROM HERE/
dbexit();
I'm new to c++ programming, I have the script above where I want to execute a SP with one parameter, passing the information of the 'db_user'.
can anyone guide my how to script it.
Database: mssql 2008
to connect to database and execute various pl/sql command (including stored procedure call) every vendor provides ODBC driver. In your question it is not clear where you are using the ODBC driver in your code and to what database you are trying to connect to. Frist check ODBC driver for your database and read vendor provided documentation/manual about how to use their driver with some examples. Every ODBC driver API are different and codes to execute pl/sql will also be different for different vendor provided ODBC driver APIs. Some third party provided ODBC driver APIs are generic for all the different database and you no need to write separate codes for different database, only database connecting string is different. One of them is datadirect. Read first vendor provided material on ODBC driver and you will get all the information in it. Wish you all the very best.

C++ Qt sql lite database connection issue

The following code is used by me to connect to a database using Qt IDE. And if it successfully connects to the database Connected to db is printed on a label. But the issue is if I even given a wrong database path it returns Connected to db on the label how can i correct this issue?
QSqlDatabase mydb= QSqlDatabase::addDatabase("QSQLITE");
mydb.setDatabaseName("x");
if(!mydb.open()){
ui->label->setText("Failed to open the db");
}
else{
ui->label->setText("Connected to db");
}
Even though in the above code i put "x" which is not a valid database path I get "Connected to db' in the label when I run the program!
How can i correct this issue?
Qt uses as SQLite backend uses the sqlite library, so you will use one of the functions to open the database:
int sqlite3_open(
const char *filename, /* Database filename (UTF-8) */
sqlite3 **ppDb /* OUT: SQLite db handle */
);
int sqlite3_open16(
const void *filename, /* Database filename (UTF-16) */
sqlite3 **ppDb /* OUT: SQLite db handle */
);
int sqlite3_open_v2(
const char *filename, /* Database filename (UTF-8) */
sqlite3 **ppDb, /* OUT: SQLite db handle */
int flags, /* Flags */
const char *zVfs /* Name of VFS module to use */
);
According to the docs:
These routines open an SQLite database file as specified by the
filename argument. The filename argument is interpreted as UTF-8 for
sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte
order for sqlite3_open16(). A database connection handle is usually
returned in *ppDb, even if an error occurs. The only exception is that
if SQLite is unable to allocate memory to hold the sqlite3 object, a
NULL will be written into *ppDb instead of a pointer to the sqlite3
object. If the database is opened (and/or created) successfully, then
SQLITE_OK is returned. Otherwise an error code is returned. The
sqlite3_errmsg() or sqlite3_errmsg16() routines can be used to obtain
an English language description of the error following a failure of
any of the sqlite3_open() routines.
From which we conclude that if the database does not exist this will create it, it will only generate the error in creating it if there are problems to allocate memory.

How can I execute an SQLite statement in C++

I have the following command which works fine on Linux Console. But to get the result to a cpp file I have to store it to file and then read it. But is there a way I can directly execute this command in C++.
/usr/bin/sqlite3 /etc/myDB/db/share.db "select path from folder_info where ftp='YES'"
As far as i understand your question you can use the SQLite3 c++ api which is described here
How can I execute an SQLite statement in C++
using stringstream
An Introduction To The SQLite C/C++ Interface
sqlite3 *db;
sqlite3_open("dbfile.db", &db);
sqlite3_stmt *companydetails;
std::stringstream companystr;
companystr << "select companyname,companydetails from company";
sqlite3_prepare(db, companystr.str().c_str(), companystr.str().size(),&companydetails, NULL);
sqlite3_step(companydetails);

Good C/C++ connector library for PostgreSQL [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking us to recommend or find a book, tool, software library, tutorial or other off-site resource are off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead, describe the problem and what has been done so far to solve it.
Closed 8 years ago.
Improve this question
My application is a commercial GIS C++ application, and I'm looking for a robust/easy to use connector for Postgresq. (Side note: I also plan to use PostGIS)
Does anyone have any recommendations based on your experience? A plus would be if you have tried out various ones.
I have looked at:
Postgres's C client
pqxx
QSql
EDIT
Also, does anyone know what's a good admin GUI tool? I see a community list here. But there are so many! I'm developing on Windows, and dont mind paying for commercial tools.
Someone in another Stackoverflow post suggested Maestro.
libpq++ is one provide very good connector for PostgreSQL
SQLAPI++ is a C++ library for accessing multiple SQL databases (Oracle, SQL Server, DB2, Sybase, Informix, InterBase, SQLBase, MySQL, PostgreSQL and ODBC, SQLite).
Abstract Database Connector is a C/C++ library for making connections to several databases (MySQL, mSQL, PostgreSQL, Interbase, Informix, BDE, ODBC). It runs on Linux, UNIX, BeOS, and Windows, and a dynamic driver loader for ELF OSes is under development
Navicat is Nice GUI tool for PostgrSQL
Take a look at SOCI. Is an open source lib under Boost Software License (one of the most non-restrictive licenses at all).
This lib is designed especially for C++ with the idea of generic programming and type safety in mind.
SOCI Site
I wrote a wrapper around libpq for our needs. I was a long time Zeoslib (http://sourceforge.net/projects/zeoslib/) but they were riped with problems last I used them, didn't support cached datasets and plain slow.
libpq is very, very fast.
I simply download the Windows version of Postgres, copy all the DLLs to a lib directory and export the calls, include the .h and link accordingly.
I realize this is very low level but I can't emphasize enough the performance increase I'm realizing as a result.
Our application is an accounting/ERP type business application with fairly large install base some with fairly significant concurrent many user base (60, 100 connections)... This has served us very well... You can reply back if you want more details on how we wrap libpq and handle cached updates.
UPDATE:
From a request here are the steps to wrap libpq or make use of it directly under windows.
First, to level set, I use Embarcadero RAD XE these days so the commands that follow are the command line tools that ship with RAD XE. You also need to make sure that your command line tools are in the PATH environment variable if not already. If using Visual Studio, then you will have to work out the equivalent commands. Basically I'm creating a .lib file out of a .DLL
TEST.C is a minimalist test code I wrote to make sure I understood how to use libpq and also to test my success.
1. Put all the DLLs into a directory and copy the include directory.
You do not need to install PostgreSQL using the MSI build to get these DLLs, although that would work too. I copied the DLLs from the binary build. The .H files were also taken from the binary build as well. So my directory looks like this:
include\
libpq-fe.h
postgres_ext.h
libeay32.dll
libiconv-2.dll
libintl-8.dll
libpq.dll
ssleay32.dll
zlib1.dll
2. Create an import library against LIBPQ.DLL as follows:
implib -c -a libpq.lib libpq.dll
should now have a libpq.lib file in the same directory as your DLLs.
3. build the test program (or any program) as follows:
bcc32 test.c -l libpq.lib
test.c
#include <stdio.h>
#include "include/libpq-fe.h"
char *db = "mydatabasename";
char *dbserver = "hostname";
char *uname = "username";
char *pass = "password";
char *SQL = "select * from public.auditlog;";
// char *SQL = "select userid, stationid from public.auditlog";
char buff[200];
PGconn *dbconn;
PGresult *res;
void main(void)
{
int nFields, i, j;
printf("Attempting to Connect to Database Server:\n");
printf("Database: %s\n", db);
printf("Server : %s\n", dbserver);
sprintf(buff, "dbname=%s host=%s port=5432 user=%s password=%s",
db, dbserver, uname, pass);
dbconn = PQconnectdb(buff);
if( PQstatus(dbconn) != CONNECTION_OK )
printf("Connection Failed: %s\n", PQerrorMessage(dbconn) );
else
{
printf("Connected Successfully!\n");
sprintf(buff, "BEGIN; DECLARE my_portal CURSOR FOR %s", SQL);
res = PQexec(dbconn, buff);
if( PQresultStatus(res) != PGRES_COMMAND_OK )
{
printf("Error executing SQL!: %s\n", PQerrorMessage(dbconn) );
PQclear(res);
}
else
{
PQclear(res);
res = PQexec(dbconn, "FETCH ALL in my_portal" );
if( PQresultStatus(res) != PGRES_TUPLES_OK )
{
printf("ERROR, Fetch All Failed: %s", PQerrorMessage(dbconn) );
PQclear(res);
}
else
{
nFields = PQnfields(res);
// Print out the field names
for(i=0; i<nFields; i++ )
printf("%-15s", PQfname(res, i) );
printf("\n");
// Print out the rows
for(i=0; i<PQntuples(res); i++)
{
for(j=0; j<nFields; j++)
printf("%-15s", PQgetvalue(res, i, j) );
printf("\n");
}
res = PQexec(dbconn, "END" );
PQclear(res);
}
}
}
PQfinish(dbconn);
}
Now to access a PostgreSQL system I simply copy the libpq.lib file into any new RAD-XE project and add the libpq.lib to the project. I have wrapped the libpq into a database transport driver that sort of separates my database access code away.
The following screen shot shows a RAD-XE project called ptidb that, in turn, uses libpq to provide PostgreSQL support. I also support SQLite except with SQLite I just compile the database directly.
Then I simply ship the DLLs, listed above, along with my final product making sure the DLLs wind up in the same directory as my product.
This should get you going. If you're also interested in the C++ wrapping I do, let me know and I'll post another update with some of it.