SQL/C++ Programming

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include <stdlib.h>
#include <iostream>
#include <cstring>
#include <string>

/*
  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)
{

  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", "ilovefatin");
  con->setSchema("Filter");
  

  stmt = con->createStatement();
  string No = "111";
  res = stmt->executeQuery("SELECT * FROM Tasks WHERE Notes = '"No.c_str()"' ");


  while (res->next())
  {

      cout << "Notes " << res->getInt(1) << " " ;
      cout << "ID " << res->getString("TaskID") << endl;



  }
  
  delete res;
  delete stmt;
  delete con;


return EXIT_SUCCESS;
}


Hey guys , the problem which i am facing is that i would like to use a variable in order to base my SELECT statement upon. I am not sure how to go about getting it to be accepted by the SQL syntax. Hope for some help here. I tried using c_str() , but it does not seem to be working. How can i fix this in order for my SELECT statement to search based on my variable.
It's a string right? Do know how to format a string?

Just encase you don't, you can build the string using + or you can format it using a string stream.

e.g.
1
2
3
4
std::string sql = "SELECT * FROM Tasks WHERE Notes = ";
sql += "\'";
sql += No
sql + "\'";

or:
1
2
3
std::ostringstream os;
os << "SELECT * FROM Tasks WHERE Notes = \'" << No << "\'";
std::string sql = os.str();


then:
 
stmt->executeQuery(sql.c_str());


EDIT: Who's fatin?
Last edited on
Topic archived. No new replies allowed.