having issues inserting data in Mysql from C++ in Linux - c++

Can anyone help me get through just inserting a record with C++ in Linux using the #include<mysql.h> , i have tried almost everything possible , it works just fine making the columns static but cannot pass variables to them at all , even with a cin statement. tried using cin.get(char &ch): and also cin >> varname, why is this so difficult. ? what am i missing.
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <string>
#include <iomanip>
#include <stdio.h>
#include <time.h>
// For MySQL Connection
#include <mysql.h>
using namespace std;
int trollyid = 88232;
// Defining Constant Variables Future Revisions with be with reading a json File
#define SERVER "localhost"
#define USER "root"
#define PASSWORD "xxxxx"
#define DATABASE "txxxx"
int main()
{
MYSQL *connect;
connect = mysql_init(NULL);
auto time = std::time(nullptr);
int trollyid = 88232;
if (!connect)
{
cout << "Mysql Initialization Failed";
// Write XML log for failure
return 1;
}
connect = mysql_real_connect(connect, SERVER, USER, PASSWORD, DATABASE, 0,NULL,0);
if (connect)
{
cout << "Connection Succeeded\n";
}
else
{
cout << "Connection Failed\n";
}
MYSQL_RES *res_set;
MYSQL_ROW row;
// MySQL query with your query
// -- Need to pass variables into the two field '665566', 'GOOD')
mysql_query (connect,"INSERT INTO `Datalog` (`id`, `datecol`, `timecol`, `trolleyid`,
`status`) VALUES (NULL, NOW(), NOW(), '665566', 'GOOD')");
// update: table Datalog with data VALUES (NULL, NOW(), NOW(), '4444444', 'GOOD')");
res_set=mysql_store_result(connect);
// --------------Just showing tables on testing (Move
along)---------------------------------
// unsigned int numrows = mysql_num_rows(res_set);
// cout << " Tables in " << DATABASE << " database " << endl;
// while (((row=mysql_fetch_row(res_set)) !=NULL))
// {
// cout << row[i] << endl;
//}
std::cout
// ISO 8601: %Y-%m-%d %H:%M:%S, e.g. 2017-07-31 00:42:00+0200.
<< std::put_time(std::gmtime(&time), "%H:%M:%S") << '\n'
// %m/%d/%y, e.g. 07/31/17
<< std::put_time(std::gmtime(&time), "%D");
mysql_close (connect);
return 0;
}
// ** EXAMPLE **
// TEST INPUT to table:
char status[20];
cin >> nValue;
cin >> status;
cin.getline(status, sizeof(name)); //taking string input
// MySQL query with your query
mysql_query (connect,"INSERT INTO `Datalog` (`id`, `datecol`, `timecol`, `trolleyid`, `status`) VALUES (NULL, NOW(), NOW(), 'nValue', 'status')");
so here is the way it works now, can i put these back into an array ?
[code][1]

Related

How can I connect to my SQL Database through C++?

I've seen some similar questions but most are based around PHP, there was one based around C but the only answer was go to the SQLConnect() docs, which I've already done.
https://learn.microsoft.com/en-us/sql/odbc/reference/syntax/sqlconnect-function?redirectedfrom=MSDN&view=sql-server-ver15
Seems to be little content online, also I'm a beginner so excuse any silly issues.
I set up the SQL database using the MYSQL Workbench and it's sitting on my localhost:3306. I was able to connect it to the ODBC Data Source Admin program successfully.
So I believe I'm using the right function and have the right SQL back end set up, I just don't know where to go from here.
The end goal is to be able to 'insert' records into my database with the program and also 'select' from it too.
What am I doing wrong, or what am I missing?
# include <stdio.h>
# include <stdlib.h>
# include <sql.h>
# include <sqlext.h>
# include <cstdio>
# include <cstdint>
using namespace std;
int main(){
SQLHENV henv = NULL;
SQLHDBC hdbc = NULL;
/* Initialize the ODBC environment handle. */
SQLAllocHandle(SQL_HANDLE_ENV, NULL, &henv);
/* Set the ODBC version to version 3 (the highest version) */
SQLSetEnvAttr(henv, SQL_ATTR_ODBC_VERSION,
(void*)SQL_OV_ODBC3, 0);
/* Allocate the connection handle. */
SQLAllocHandle(SQL_HANDLE_DBC, henv, &hdbc);
SQLConnectW(hdbc, (SQLWCHAR*)"localhost", (SQLSMALLINT) 9,
(SQLWCHAR*)"root", (SQLSMALLINT)4,
(SQLWCHAR*)"password", (SQLSMALLINT)8);
return(0);
}
I have added the comments inside the code, which will help you to understand the code easily.
Credits: Link
/* Includes Standard C++ */
#include <stdlib.h>
#include <iostream>
/*
Include directly the different
headers from cppconn/ and mysql_driver.h + mysql_util.h
(and mysql_connection.h). This will reduce your build time!
*/
#include "mysql_connection.h"
#include <cppconn/driver.h>
#include <cppconn/exception.h>
#include <cppconn/resultset.h>
#include <cppconn/statement.h>
using namespace std;
int main(void)
{
cout << endl;
cout << "Running 'SELECT 'Successfull' »
AS _message'..." << endl;
try {
sql::Driver *driver;
sql::Connection *con;
sql::Statement *stmt;
sql::ResultSet *res;
/* Create a connection */
driver = get_driver_instance();
con = driver->connect("tcp://127.0.0.1:3306", "root", "root");
/* Connect to the MySQL test database */
con->setSchema("test");
stmt = con->createStatement();
res = stmt->executeQuery("SELECT 'Successfull' AS _message"); // replace with your statement
while (res->next()) {
cout << "\t... MySQL replies: ";
/* Access column data by alias or column name */
cout << res->getString("_message") << endl;
cout << "\t... MySQL says it again: ";
/* Access column fata by numeric offset, 1 is the first column */
cout << res->getString(1) << endl;
}
delete res;
delete stmt;
delete con;
} catch (sql::SQLException &e) {
cout << "# ERR: SQLException in " << __FILE__;
cout << "(" << __FUNCTION__ << ") on line " »
<< __LINE__ << endl;
cout << "# ERR: " << e.what();
cout << " (MySQL error code: " << e.getErrorCode();
cout << ", SQLState: " << e.getSQLState() << " )" << endl;
}
cout << endl;
return EXIT_SUCCESS;
}

How can I pass user-defined variable into MySQL Database Table using C++?

I have created MySQL Database, I would like to add user-defined variables(age and grade) into the database table. I couldn't figure out how to include variables into the table in my database.
The code is pasted below.
#include <iostream>
#include <windows.h>
#include <mysql.h>
#include <string>
using namespace std;
int main()
{
MYSQL* conn;
conn = mysql_init(0);
conn = mysql_real_connect(conn, "127.0.0.1", "root", "password", "test", 0, NULL, 0);
if (conn)
{
cout << "Connected" << endl;
}
else
cout << "Not Connected";
int grade;
int age;
cout << "Enter Age and Grade" << endl;
cin >> age;
cin >> grade;
mysql_query(conn, "CREATE TABLE test1 ( AGE INT, GRADE INT)");
mysql_query(conn, "INSERT INTO test (AGE, GRADE) VALUES (age, grade)"; //I am asking about this part
mysql_close(conn);
return 0;
}
I am not very familiar with the MySQL library, but according to their documentation for the function you are using, I think you should simply create a function that creates a statement that you can format to your liking. You could use sprintf.
For those who are looking for an answer (there can be syntax mistake, due to stack overflow indentation system).
#include <iostream>
#include <windows.h>
#include <mysql.h>
#include <string>
using namespace std;
int main()
{
MYSQL* conn;
conn = mysql_init(0);
conn = mysql_real_connect(conn, "127.0.0.1", "root", "password", "test", 0, NULL, 0);
if (conn)
{
cout << "Connected" << endl;
}
else
cout << "Not Connected";
string name;
string city;
cout << "Enter name and city: " << endl;
cin >> name;
cin >> city;
mysql_query(conn, "CREATE TABLE test1 ( NAME VARCAR (50), CITY CARCHAR (50)");
mysql_query(conn, "INSERT INTO test ('NAME', 'CITY') VALUES ('"+age+"',
'"+grade+"'))";
mysql_close(conn);
return 0;
}

structuring C++ program with mysql connections

I'm trying to create a c++ program that connects to mysql and can perform operations on the database such as add remove and edit.
For each table, I want to be able to add, remove and edit as well as run specific querys to my needs.
So far, I have everything in a single main file as I cannot figure out how to divide up my code to have one connection, and then be able to call other classes to run querys.
I clearly a beginner in C++ and am looking for some input into what I should have in each class
#include <stdlib.h>
#include <iostream>
#include "mysql_connection.h"
#include "cppconn/driver.h"
#include "cppconn/exception.h"
#include "cppconn/resultset.h"
#include "cppconn/statement.h"
using namespace std;
int main(void)
{
cout << endl;
try {
sql::Driver *driver;
sql::Connection *con;
sql::Statement *stmt;
sql::ResultSet *res;
/* Create a connection */
driver = get_driver_instance();
con = driver->connect("tcp://127.0.0.1:3306", "root", "root");
/* Connect to the MySQL test database */
con->setSchema("ParkSmart");
stmt = con->createStatement();
res = stmt->executeQuery("SELECT * FROM user WHERE userID = 9");
while (res->next()) {
cout << res->getString(2) << endl;
// getInt(1) returns the first column
// ... or column names for accessing results.
}
//add person(int personID, string fname, string lname)
try
{
int personID = 9;
string fname = "test";
string lname = "man";
string query = "SELECT * FROM person WHERE personID = " + to_string(personID);
res = stmt->executeQuery(query);
if (res->next()){
cout << "A person with that" << endl;
return 0;
//failure, already exists
}
else {
string query = "INSERT INTO user (personID, fname, lname) VALUES (" + to_string(personID) + ", '" + fname + "', '" + lname + ")" ;
res = stmt->executeQuery(query);
return 1;
//success, user added in to database
}
}
catch (sql::SQLException &e) {
cout << "Exception caught: no query returned" << endl;
//this is when there is no user with that userID, continue
//check for other more specific errors
}
What I am thinking is a main that calls a person class that connects to mysql and for each table there is a class that has its own connection but I'm getting seg faults
The code that I have can connect and edit the database properly, I am just lost on the actual file structures.
Any help or advice is appreciated!

#include <mysql.h> in Eclipse for C++ doesn't work - how to configure it ?

Given the following :
// Include Header Files
#include <iostream>
#include <cstdio>
#include <cstdlib>
// For MySQL Connection
#include <mysql.h>
using namespace std;
// Defining Constant Variables
#define SERVER "localhost"
#define USER "root"
#define PASSWORD "password"
#define DATABASE "test"
int main()
{
MYSQL *connect;
connect = mysql_init(NULL);
if (!connect)
{
cout << "Mysql Initialization Failed";
return 1;
}
connect = mysql_real_connect(connect, SERVER, USER, PASSWORD, DATABASE, 0,NULL,0);
if (connect)
{
cout << "Connection Succeeded\n";
}
else
{
cout << "Connection Failed\n";
}
MYSQL_RES *res_set;
MYSQL_ROW row;
// Replace MySQL query with your query
mysql_query (connect,"show tables");
unsigned int i=0;
res_set=mysql_store_result(connect);
unsigned int numrows = mysql_num_rows(res_set);
cout << " Tables in " << DATABASE << " database " << endl;
while (((row=mysql_fetch_row(res_set)) !=NULL))
{
cout << row[i] << endl;
}
mysql_close (connect);
return 0;
}
The following include : #include <mysql.h> produces Unresolved inclusion: <mysql.h> .
Any idea how resolve this ?
You have to configure the include path of Eclipse to let it find the file mysql.h.

Simple solutions for integrating MySQL with C++?

What solutions are there for making a simple connection to a MySQL database in C++?
I find MySQL Connector from dev.mysql.com hard to integrate.
Anticipated thanks!
Its pretty simple to communicate with MySQL from C/C++ application
you need to include mysql.h header file
three basic APIs to connect and execute query
mysql_connect()
mysql_query()
mysql_close()
Link with mysql library (libMysql)
You could try the ODBC path, with a support library.
Some year ago I used OTL to interface SqlServer and found it efficient. Now I've tried to interface MySql, without any problem so far:
#include <otlv4.h>
#include <iostream>
using namespace std;
int otl_x_sql_main(int argc, char **argv)
{
otl_connect db; // connect object
otl_connect::otl_initialize(); // initialize ODBC environment
try {
db.rlogon("DRIVER=mysql;DB=...;UID=...;PWD=..."); // connect to ODBC
// parametrized SELECT
otl_stream i(50, "SELECT product_id,model FROM product WHERE product_id >= :f<int> AND product_id < :ff<int>", db);
int product_id;
char model[100];
i << 1000 << 2000; // assigning product_id range
// SELECT automatically executes when all input variables are assigned
while (!i.eof()) {
i >> product_id >> model;
cout << "product_id=" << product_id << ", model=" << model << endl;
}
}
catch(otl_exception& p) { // intercept OTL exceptions
cerr << p.msg << endl; // print out error message
cerr << p.stm_text << endl; // print out SQL that caused the error
cerr << p.sqlstate << endl; // print out SQLSTATE message
cerr << p.var_info << endl; // print out the variable that caused the error
}
return 0;
}