I am trying to write a program to output a row from a MYSQL table and it always outputs the same thing...
The function takes input from another function
C++
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", "TSA!");
/* Connect to the MySQL test database */
con->setSchema("main");
stmt = con->createStatement();
stmt->execute("CALL getData('" + quest1 +"', #ans)");
res = stmt->executeQuery("SELECT #ans AS _message");
while (res->next()) {
cout << "Answer: ";
/* Access column data by alias or column name */
cout << res->getString("_message") << endl;
}
delete res;
delete stmt;
delete con;
}
and then a error statement which is not triggered by this program.
MySQL
CREATE DEFINER=`root`#`localhost` PROCEDURE `getData`(IN info MEDIUMTEXT,
OUT datas MEDIUMTEXT)
BEGIN
SELECT `answer` from `approved` WHERE `Question` = info into datas;
END
The table:
question | answer
test | test
test2 | test2
The program always and only outputs "test"
How do I fix this?
I fixed it by getting a char from the user for input using cin.getline rather than cin to a string.
You can clear the existing buffer with cin which I believe was the problem.
Related
When i dont use get_driver_instance i get segmentation fault.
I'm using linux and installed mysqlserver and connector using console commands. Any ideas how to fix this?
/usr/bin/ld: /tmp/ccXisL1A.o: in function main': test.cpp:(.text+0x5e): undefined reference to get_driver_instance'
collect2: error: ld returned 1 exit status
#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>
int main()
{
std::cout << std::endl;
std::cout << "Running Hello World!"<< std::endl;
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", "1234");
/* Connect to the MySQL test database */
con->setSchema("test1");
stmt = con->createStatement();
res = stmt->executeQuery("SELECT 'Hello World!' AS _message");
while (res->next()) {
std::cout << "\t... MySQL replies: ";
/* Access column data by alias or column name */
std::cout << res->getString("_message") << std::endl;
std::cout << "\t... MySQL says it again: ";
/* Access column data by numeric offset, 1 is the first column */
std::cout << res->getString(1) << std::endl;
}
delete res;
delete stmt;
delete con;
}
I am trying to read data from a database using the 8.0.13 MySQL C++ Connector. I am able to successfully write to a database no problem, but when I try to get the results of the database (using result next) it never runs.
bool outPutBool;
string outPut;
try {
sql::Driver *driver;
sql::Connection *con;
sql::Statement *stmt;
sql::ResultSet *res;
string test = getTest();
/* Create a connection */
driver = get_driver_instance();
con = driver->connect("tcp://ip:port", "root", "password");
/* Connect to the MySQL test database */
con->setSchema("database name");
stmt = con->createStatement();
res = stmt->executeQuery("SELECT `column name` FROM `table name` WHERE `test column` = '" + variable + "'"); //Variable is defined in the function input
while (res->next()) {
outPut = res->getString(1);
cout << outPut << endl;
cout << "Test\n"; //never runs
}
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;
}
Sleep(10000); //Temporary delay so I can see if anything comes up before it runs another function
if (test != outPut)
doSomething();
else
doSomethingElse();
The while loop never runs and I am clueless to why this happens as it seems to work for a lot of other people. I have included all libraries and headers in the connector library, but to no help.
Using the SQL Query function in phpmyadmin properly displays the output, so it's not the query's fault.
I would greatly appreciate it if anyone could give me some help here, and if you have any questions or need more of my code just ask. Thanks a lot for the help!
I'm not sure how, but after just simply adding a cout statement between the query and the while loop it suddenly solved itself. I removed the cout and now it's works perfectly no problem. Not sure what caused this error, but I'm happy that it solved itself after I have been trying to fix it for quite a while!
When you concatenate an SQL statement dynamically and when it then does not return the results you are expecting, it is very often that the generated SQL statement is not as you expected to be.
It's hard to tell what's wrong, because we cannot reproduce it without your DBMS, of course.
But usually one will write the SQL statement to stdout, copy it to an interactive SQL console then and see what happens:
std::string query = "SELECT `column name` FROM `table name` WHERE `test column` = '" + variable + "'";
std::cout << query << std::endl; // open console and copy/paste it to your DBMS
res = stmt->executeQuery(query); //Variable is defined in the function input
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!
In php I create a config file that opens a connection to the database and then I use that file in all my other files in order to open a connection also. But I can't seem to find a way to do the same thing with c++. I can connect to the database but I can't use it as a class because I have a main() inside it and I can't seem to make it work without the main. This is my code:
// Standard C++ includes
#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;
// Include the Connector/C++ headers
#include "cppconn/driver.h"
#include "cppconn/exception.h"
#include "cppconn/resultset.h"
#include "cppconn/statement.h"
// Link to the Connector/C++ library
#pragma comment(lib, "mysqlcppconn.lib")
// Specify our connection target and credentials
const string server = "localhost";
const string username = "root";
const string password = "";
int main()
{
sql::Driver *driver; // Create a pointer to a MySQL driver object
sql::Connection *dbConn; // Create a pointer to a database connection object
sql::Statement *stmt; // Create a pointer to a Statement object to hold our SQL commands
sql::ResultSet *res; // Create a pointer to a ResultSet object to hold the results of any queries we run
// Try to get a driver to use to connect to our DBMS
try
{
driver = get_driver_instance();
}
catch (sql::SQLException e)
{
cout << "Could not get a database driver. Error message: " << e.what() << endl;
system("pause");
exit(1);
}
// Try to connect to the DBMS server
try
{
dbConn = driver->connect(server, username, password);
}
catch (sql::SQLException e)
{
cout << "Could not connect to database. Error message: " << e.what() << endl;
system("pause");
exit(1);
}
stmt = dbConn->createStatement();
// Try to query the database
try
{
stmt->execute("USE test");
res = stmt->executeQuery("SELECT * FROM users");
}
catch (sql::SQLException e)
{
cout << "SQL error. Error message: " << e.what() << endl;
system("pause");
exit(1);
}
sql::ResultSetMetaData *res_meta = res -> getMetaData();
int columns = res_meta -> getColumnCount();
while (res->next())
{
for (int i = 1; i <= columns; i++) {
cout << res->getString(i) << " | " ;
}
cout << endl;
}
delete res;
delete stmt;
delete dbConn;
return 0;
}
You need to create a class (e.g class DBConnector)and declare functions in header file.
For example this piece of code can go into one function:
sql::Driver* DBConnector::GetDriverInstance()
{
try
{
m_driver = get_driver_instance();
}
catch (sql::SQLException e)
{
cout << "Could not get a database driver. Error message: " << e.what() << endl;
system("pause");
exit(1);
}
return m_driver;
}
Here sql::Driver *m_driver is expected to be declared as a member variable of class in header file. You might need to read more about classes and member functions and variables before actually going ahead with code.
Other than this, you need to take very good care of memory management. I would suggest you read more and use smart pointers like std::shared_ptr.
error: ‘sql’ does not name a type
sql::Connection connect_mysql();
Is there a way i can return the connection object from this function?
I know to return the connection object in C but not happening in C++.
edited version: return type of connect_mysql() has been changed to sql::Connection * . earlier it was sql::Connection.
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <string.h>
#include<mysql/mysql.h>
#include<cppconn/driver.h>
#include<cppconn/exception.h>
#include<cppconn/resultset.h>
#include<cppconn/statement.h>
sql::Connection * connect_mysql();
int main()
{
sql::Connection *con;
con = connect_mysql();
return 0;
}
sql::Connection * connect_mysql()
{
cout << "CONNECTING DATABASE..............."<<endl;
try{
cout<<"inside try while connecting to mysql"<<endl;
sql::Driver *driver;
sql::Connection *con;
sql::Statement *stmt;
sql::ResultSet *res;
driver = get_driver_instance();
con = driver->connect("localhost","root","Aricent#123");
con->setSchema( "COE" );
stmt = con->createStatement();
res = stmt->executeQuery( "show tables" );
while( res->next() )
{
cout<<"MYSQL replies:"<<endl;
cout<<res->getInt(1);
cout<<res->getString(1)<<endl;
}
}
catch( exception e )
{
cout << "# ERR: SQLException in " << __FILE__;
cout << "# ERR: ";
cout << " (MySQL error code: ";
cout << ", SQLState: ";
}
return con;
}
That's not an object, it's a pointer. Try this
sql::Connection* connect_mysql()
{
...
}
Another error is the lack of prototype for connect_mysql. You should have something like this
sql::Connection* connect_mysql(); // prototype
int main()
{
sql::Connection *con;
con = connect_mysql();
...
But what is confusing me about your error message is that it refers to the line sql::Connection* connect_mysql() but apparently using the same type in the line sql::Connection *con; is OK. If you have any other error messages or warnings please post those as well.
It shouldn't need stating that for help with compiler error messages you should post the exact code, the exact error messages, and all of both of those.
I'm not an expert on mysql but I wonder if you need a header file #include <cppconn/connection.h>