database in c++ with sqlite3 - c++

I am working on my coursework for my university. It consists on making a database in c++. I have those errors from Monday and I can not solve them.
Can anyone help me to fix this issue, please?
I am working in VSCode and I am a beginner in c++, thank you.
code:
#include <stdio.h>
#include <D:\SSD\Desctop\barethika\sqlite3.h>
int main(int argc, char* argv[]) {
sqlite3 *db;
char *zErrMsg = 0;
int rc;
rc = sqlite3_open("test.db", &db);
if( rc ) {
fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
return(0);
} else {
fprintf(stderr, "Opened database successfully\n");
}
sqlite3_close(db);
}
ERRORS:
c:\users\name\AppData\Local\Temp\ccguCZxk.o:tempCodeRunnerFile.cpp(.text+00xa4)
undefined reference to 'sqlite3_open'
c:\users\name\AppData\Local\Temp\ccguCZxk.o:tempCodeRunnerFile.cpp(.text+00xa4)
undefined reference to 'sqlite3_errmsg'
c:\users\name\AppData\Local\Temp\ccguCZxk.o:tempCodeRunnerFile.cpp(.text+00xa4)
undefined reference to 'sqlite3_close' collect2.exe:error: ld returned
1 exit status

Try to set the absolute path of the library. This kind of problem is usually the wrong path of the library

Related

Undefined reference to Eclipse C++ with libraries MySQL Server and Connector C++

As it is my first question on the forum, please be forgiving with style issues.
I've been looking for information to solve this but the problem hasn't reached a solution. I ask here in the hope someone will know. In need of implementing a MySQL database inside a C++ environment, I've followed the steps in this video, about how to setup MySQL in such a way. However, when trying to build the simple .cpp used there I've been unable to achieve in making it work. From what I have been reading, I can tell my errors are related to the linker, but I do not know how to correct them.
It may not be important, but note that I use Eclipse in contrast to the person of the video, that works with Visual Studio.
Error from console:
C:\Users\quimi\Desktop\eclipse\AskACountryC++\Debug/../MySqlTest.cpp:15: undefined reference to `mysql_init#4'
C:\Users\quimi\Desktop\eclipse\AskACountryC++\Debug/../MySqlTest.cpp:17: undefined reference to `mysql_real_connect#32'
C:\Users\quimi\Desktop\eclipse\AskACountryC++\Debug/../MySqlTest.cpp:24: undefined reference to `mysql_query#8'
C:\Users\quimi\Desktop\eclipse\AskACountryC++\Debug/../MySqlTest.cpp:27: undefined reference to `mysql_store_result#4'
C:\Users\quimi\Desktop\eclipse\AskACountryC++\Debug/../MySqlTest.cpp:28: undefined reference to `mysql_fetch_row#4'
C:\Users\quimi\Desktop\eclipse\AskACountryC++\Debug/../MySqlTest.cpp:35: undefined reference to `mysql_error#4'
The project's Include paths in GCC C++ Compiler:
"C:\Program Files\MySQL\MySQL Server 8.0\include"
"C:\Program Files\MySQL\Connector C++ 8.0\include"
The Libraries in MinGW C++ Linker:
:libmysql.lib
:mysqlcppconn.lib
And the Library search path in MinGW C++ Linker:
"C:\Program Files\MySQL\MySQL Server 8.0\lib"
"C:\Program Files\MySQL\Connector C++ 8.0\lib64\vs14"
Any idea about what can be happening and what could be a solution? Anything would be appreciated.
The .cpp:
#include <mysql.h>
#include <iostream>
using namespace std;
int qstate;
int main()
{
MYSQL* conn;
MYSQL_ROW row;
MYSQL_RES *res;
conn = mysql_init(0);
conn = mysql_real_connect(conn, "localhost", "root", "password", "testdb", 3306, NULL, 0);
if (conn) {
puts("Successful connection to database!");
string query = "SELECT * FROM test";
const char* q = query.c_str();
qstate = mysql_query(conn, q);
if (!qstate)
{
res = mysql_store_result(conn);
while (row = mysql_fetch_row(res))
{
printf("ID: %s, Name: %s, Value: %s\n", row[0], row[1], row[2]);
}
}
else
{
cout << "Query failed: " << mysql_error(conn) << endl;
}
}
else {
puts("Connection to database has failed!");
}
return 0;
}

C++ cannot find SQLite3

I am trying to use SQLite with c++ on windows. My code looks like this
#include <stdio.h>
#include <sqlite3.h>
int main(int argc, char* argv[])
{
sqlite3 *db;
char *zErrMsg = 0;
int rc;
rc = sqlite3_open("test.db", &db);
if( rc ){
fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
return(0);
}else{
fprintf(stderr, "Opened database successfully\n");
}
sqlite3_close(db);
}
which returns the error message
C:\sqlite: No such file or directory
compilation terminated.
There have been several other stackoverflow questions on this but they were all solved by changing #include <sqlite3.h> to #include "sqlite3.h" or #include <full_path_to_sqlite3>, none of which work
One was also solved by including -lsqlite3 when compiling, but this returns
c:/mingw/bin/../lib/gcc/mingw32/5.3.0/../../../../mingw32/bin/ld.exe: cannot find -lsqlite3
collect2.exe: error: ld returned 1 exit status
which is odd to me because sqlite3 works just fine for me normally in cmd
How do I fix this?
This is a linking problem basically.
Example solutions:
Make sure the compiler actually sees the sqlite includes
If you haven't already, add the library headers folder to the Additional
include directories
Etc.
Just go step by step and make sure everything is in place.

Sqlite: Execute Spatialite Functions in Qt5.4.2 or vs2010 along with Qt-addin

Does anyone know whether it is possible to execute spatialite functions on sqlite-databases in Qt5 or visual studio 2010 along with Qt-addin?
In particular, I would be interested in using functions on type Point.
Thanks!
PS: Functions do work within the official spatialite-gui, however I don't think there is a way to use the spatialite-gui programmatically, is there?
Here is what I tried so far: In Qt5.4.2 I connected SQLITE spatialite database and tried using function ST_X(point), ST_Y(point), ST_PointN and ST_NumPoints with no success:
SELECT ST_X(ST_PointN(Geometry, 1)) AS StartX, ST_Y(ST_PointN(Geometry, 1)) AS StartY, ST_X(ST_PointN(Geometry, ST_NumPoints(Geometry))) AS EndX, ST_Y(ST_PointN(Geometry, ST_NumPoints(Geometry))) AS EndY FROM "国道"
Then this always cannot be excuted successfully. And I also find some relate solution about java in Sqlite: Execute Spatialite Functions in Intellij but these yet cannot solve my problem:
step 1: download mod_spatialite-4.3.0a-win-x86.7z file from spatialite website and uncompress it into c:\sqlite3
PS: In Window 10, I open sqlite3 by cmd, SQL sentence that SELECT load_extension('mod_spatialite') could be excuted successfully.
step 2: In my Qt's code, add SELECT load_extension('mod_spatialite') before SQL statement contained spatialite function. Unfortunately, return value by excute QSqlQuery.exec("SELECT load_extension('mod_spatialite')") is false. Oh no, this is a depressing message.
What's more, I also find some relate solution about Qt in https://forum.qt.io/topic/69835/why-can-t-qt-be-installed-with-sqlite-that-has-load_extension-enabled. However, This need recompile Qt from source and it beyond my skill. Finally, How do I in Qt5.4.2 or visual studio 2010 along with Qt-addin? Has anybody done this before?
The load_extension() documentation says:
For security reasons, extension loaded is turned off by default.
You have to enable it with the C function sqlite3_enable_load_extension() or sqlite3_db_config(…SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION…).
And when you're calling C functions anyway, you can also use sqlite3_load_extension().
If you are not able to call the SQLite library functions directly from your Qt application, then your only choice is to recompile Qt (or the Qt plugin).
Thanks for your help very much, particularly, #Marco and #CL..
Below is my two solution:
PS:
First of all, download mod_spatialite-4.3.0a-win-x86.7z from http://www.gaia-gis.it/gaia-sins/windows-bin-x86/. Then, copy file named mod_spatialite.dll to your project's execute content(equal to your .exe program files). Next, write your Qt project and run this Qt project to test it.
My machine runtime: Window 10 + Qt5.4.2 + Sqlite3
First Solution:
As #CL. says,
If you are not able to call the SQLite library functions directly from your Qt application, then your only choice is to recompile Qt (or the Qt plugin).
So I recompile sqlite Qt plugin (file path is C:\Qt\Qt5.4.2\5.4\Src\qtbase\src\plugins\sqldrivers). Then modify two position:
add DEFINES -= SQLITE_OMIT_LOAD_EXTENSION in sqlite.pro;
add below code block in function named open of qsql_sqlite.cpp:
if (sqlite3_open_v2(db.toUtf8().constData(), &d->access, openMode, NULL) == SQLITE_OK) {
...
char* zErrMsg = 0;
char* spatialiteDll = "mod_spatialite";
sqlite3_enable_load_extension(d->access, 1);
sqlite3_load_extension(d->access, spatialiteDll, 0, &zErrMsg);
...
}
Second Solution: Reference links: https://www.sqlite.org/quickstart.html
As #Marco says,
QSqlQuery is a c++/Qt class that you are using to get data from the sqlite database, but Qt is also c++ so you are free to use any c++ sqlite library to open you sqlite database. sqlite.org/quickstart.html
So, I get below code to execute SQL sentence along with spatialite function in Qt5.
Example Code:
#include <QCoreApplication>
#include <stdio.h>
#include <sqlite3.h>
static int callback(void *NotUsed, int argc, char **argv, char **azColName){
int i;
for(i=0; i<argc; i++){
printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
}
printf("\n");
return 0;
}
int main(int argc, char **argv){
QCoreApplication a(argc, argv);
sqlite3 *db;
char *zErrMsg = 0;
int rc;
if( argc!=3 ){
fprintf(stderr, "Usage: %s DATABASE SQL-STATEMENT\n", argv[0]);
return(1);
}
rc = sqlite3_open(argv[1], &db);
if( rc ){
fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
sqlite3_close(db);
return(1);
}
char* spatialiteDll = "mod_spatialite";
sqlite3_enable_load_extension(db, 1);
sqlite3_load_extension(db, spatialiteDll, 0, &zErrMsg);
fprintf(stderr, "sqlite3 error: %s\n", zErrMsg);
rc = sqlite3_exec(db, argv[2], callback, 0, &zErrMsg);
if( rc!=SQLITE_OK ){
fprintf(stderr, "SQL error: %s\n", zErrMsg);
sqlite3_free(zErrMsg);
}
sqlite3_close(db);
return a.exec();
}

fatal error C1083: Cannot open include file: 'boost/variant.hpp': No such file or directory

I'm working on a project due in 2 days, and for the past 2 days, I've just been searching for a way to get this to work. I'm fairly new to C++, and our Class project requires us using C++ to make 5 games, and have them export to a MySQL database for a high scores table.
The MySQL database is no problem at all. My only problem is getting C++ to connect to the MySQL database.
So here's some more info incase someone can help me.
I'm using Visual Studio 2010 and 2012 for this. (As in I have VS 2012, while my school has 2010, so I don't know if there is any compatability differences for this, but I also have VS2010).
I've been searching the web for 5 hours or more about these kind of things, like why my "#include " statement won't work, and I've learned about going into the project properties and adding different include libraries. Usually after surfing for a while, I can figure out where I went wrong, but here I've just hit a dead end, as the only help I can find with this says to include boost, which I have done, but I'm completely stumped to this point. My Friends I'm doing this class project with are getting impatient, as this is the last thing we have left to do.
So here's the things I think I should include.
My Includes for both test programs I am doing (both are the exact same)
"Additional Include Directories"
C:\Users\Damian\Desktop\boost_1_53_0\boost_1_53_0\boost
C:\Program Files\MySQL\MySQL Connector C++ 1.1.3\include
C:\Program Files\MySQL\MySQL Server 5.6\include
My Linker->"Additional Library Directories"
C:\Users\Damian\Desktop\boost_1_53_0\boost_1_53_0\boost
C:\Program Files\MySQL\MySQL Connector C++ 1.1.3\lib\opt
C:\Program Files\MySQL\MySQL Server 5.6\lib
My code for both programs I am trying to run.
This one is the one I was testing on Visual Studio 2012
#include <iostream>
#include <cstdio>
#include <cstdlib>
using namespace std;
#include <stdlib.h>
#include <Windows.h>
#include <mysql.h>
#include "mysql_connection.h"
#include <cppconn/driver.h>
#define host "localhost"
#define username "username"
#define password "password"
#define database "db_test"
int main()
{
MYSQL* conn;
conn = mysql_init( NULL );
if( conn )
{
mysql_real_connect( conn, host, username, password, database, 0, NULL, 0 );
}
MYSQL_RES* res_set;
MYSQL_ROW row;
unsigned int i;
mysql_query( conn, "SELECT * FROM tbl_clients WHERE id = 1" );
res_set = mysql_store_result( conn );
unsigned int numrows = mysql_num_rows( res_set );
if( numrows )
{
row = mysql_fetch_row( res_set );
if( row != NULL )
{
cout << "Client ID : " << row[0] << endl;
cout << "Client Name: " << row[1] << endl;
}
}
if( res_set )
{
mysql_free_result( res_set );
}
if( conn )
{
mysql_close( conn );
}
return 0;
}
This is the Code I'm trying to compile on Visual Studio 2010
#include <stdio.h>
#define W32_LEAN_AND_MEAN
#include <winsock2.h>
#include "mysql.h"
#include "mysql_connection.h"
#include <cppconn/driver.h>
#include <iostream>
// change these to suit your setup
#define TABLE_OF_INTEREST "highscores"
#define SERVER_NAME "127.0.0.1"
#define DB_USER "root"
#define DB_USERPASS "root"
#define DB_NAME "test"
// prototypes
void showTables(MYSQL*);
void showContents(MYSQL*,const char*);
using namespace std;
int main(int argc, char* argv[])
{
MYSQL *hnd=NULL; // mysql connection handle
const char *sinf=NULL; // mysql server information
hnd = mysql_init(NULL);
if (NULL == mysql_real_connect(hnd,SERVER_NAME,DB_USER,DB_USERPASS,DB_NAME,0,NULL,0))
{
fprintf(stderr,"Problem encountered connecting to the %s database on %s.\n",DB_NAME,SERVER_NAME);
}
else
{
fprintf(stdout,"Connected to the %s database on %s as user '%s'.\n",DB_NAME,SERVER_NAME,DB_USER);
sinf = mysql_get_server_info(hnd);
if (sinf != NULL)
{
fprintf(stdout,"Got server information: '%s'\n",sinf);
showTables(hnd);
showContents(hnd,TABLE_OF_INTEREST);
}
else
{
fprintf(stderr,"Failed to retrieve the server information string.\n");
}
mysql_close(hnd);
}
return 0;
}
void showTables(MYSQL *handle)
{
MYSQL_RES *result=NULL; // result of asking the database for a listing of its tables
MYSQL_ROW row; // one row from the result set
result = mysql_list_tables(handle,NULL);
row = mysql_fetch_row(result);
fprintf(stdout,"Tables found:\n\n");
while (row)
{
fprintf(stdout,"\t%s\n",row[0]);
row = mysql_fetch_row(result);
}
mysql_free_result(result);
fprintf(stdout,"\nEnd of tables\n");
return;
}
void showContents
(
MYSQL *handle,
const char *tbl
)
{
MYSQL_RES *res=NULL; // result of querying for all rows in table
MYSQL_ROW row; // one row returned
char sql[1024], // sql statement used to get all rows
commastr[2]; // to put commas in the output
int i,numf=0; // number of fields returned from the query
sprintf(sql,"select * from %s",tbl);
fprintf(stdout,"Using sql statement: '%s' to extract all rows from the specified table.\n",sql);
if (!mysql_query(handle,sql))
{
res = mysql_use_result(handle);
if (res)
{
numf = mysql_num_fields(res);
row = mysql_fetch_row(res);
fprintf(stdout,"Rows returned:\n\n");
while (row)
{
commastr[0]=commastr[1]=(char)NULL;
for (i=0;i<numf;i++)
{
if (row == NULL)
{
fprintf(stdout,"%sNULL",commastr);
}
else
{
fprintf(stdout,"%s%s",commastr,row);
}
commastr[0]=',';
}
fprintf(stdout,"\n");
row = mysql_fetch_row(res);
}
fprintf(stdout,"\nEnd of rows\n");
mysql_free_result(res);
}
else
{
fprintf(stderr,"Failed to use the result acquired!\n");
}
}
else
{
fprintf(stderr,"Failed to execute query. Ensure table is valid!\n");
}
return;
}
Now both of these give me this error
1>c:\program files\mysql\mysql connector c++ 1.1.3\include\cppconn\connection.h(31): fatal error C1083: Cannot open include file: 'boost/variant.hpp': No such file or directory
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
Please help! Note: I'm only trying to connect to the database with success so I can run different queries and whatnot. These programs are just tests that I've copied from elsewhere.
Thanks!!
I think
"Additional Include Directories"
C:\Users\Damian\Desktop\boost_1_53_0\boost_1_53_0\boost
needs to be
"Additional Include Directories"
C:\Users\Damian\Desktop\boost_1_53_0\boost_1_53_0

how connect mysql using c++

Editor's Note: Original Text:
how connect mysql using c++
#include <iostream>
#include <fstream>
#include <string>
#include "/usr/local/mysql5/include/mysql.h"
using namespace std;
int main() {
MYSQL *mysql;
MYSQL_RES *result;
MYSQL_ROW row;
string server = "192.168.1.92";
string username = "useradmin";
string password = "useradmin";
string database = "market";
int port = 3306;
mysql = mysql_init(0);
if ( !mysql_real_connect( mysql, server.c_str(), username.c_str(), password.c_str(), database.c_str(), port, NULL, 0 ) ) {
fprintf( stderr, "%s\n", mysql_error( mysql ) );
return 0;
}
if ( !mysql_query( mysql, "SELECT text, prequency FROM ma_dict" ) ) {
fprintf(stderr, "%s\n", mysql_error( mysql ) );
return 0;
}
result = mysql_use_result( mysql );
ofstream SaveFile("/tmp/dict.txt");
while ( ( row = mysql_fetch_row( result ) ) != NULL ) {
//SaveFile << fprintf( stdout, "%s\t%d", row[0], $row[1] ) << endl;
cout << row[0] << endl;
}
mysql_free_result( result );
mysql_close( mysql );
SaveFile.close();
return 1;
}
undefined reference to mysql_init'
undefined reference tomysql_real_connect'
...
Editor's Note: A translation was attempted:
I'm using Eclipse, and I get compilation errors using mysql.h. How do I link to mysql?
#include "mysql.h"
Editor's Note: English questions are required on Stack Overflow. Please do your best at translating your question to English as needed, even if you have to use an automatic translation service like Google Translate.
Editor's Note: Original Text:
信息太少了, 把编译器错误贴出来看看.
可能因为:
mysql.h不在配置的include目录中.
Mysql库文件不在link列表里面
头文件与二进制库文件不配套
Editor's Note: A translation was attempted:
There's too little information in your question. Post the actual compiler error into your question.
That being said, the error may be caused by:
Mysql.h is not in the configuration or in the include directory.
MySql database file is not in the linker's path.
Header and library files are not consistent with each other.
An issue in the sample is that mysql_query returns 0 on SUCCESS – so it always thinks an error occurred on success.
Change it to:
if ( mysql_query( mysql, "SELECT text, prequency FROM ma_dict" ) ) {