用mysql连接构建C ++程序

时间:2018-11-24 20:53:08

标签: c++ mysql class

我正在尝试创建一个连接到mysql并可以对数据库执行操作(如添加,删除和编辑)的c ++程序。 对于每个表,我希望能够添加,删除和编辑以及运行满足我需要的特定查询。 到目前为止,我将所有内容都保存在一个主文件中,因为我无法弄清楚如何将代码分割成一个连接,然后能够调用其他类来运行查询。 我显然是C ++的初学者,并且正在寻找有关每个班级应有的知识

  #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
     }

我在想的是一个主函数,它调用连接到mysql的人员类,并且对于每个表都有一个具有自己的连接的类,但是我遇到了段错误

我拥有的代码可以正确连接和编辑数据库,我只是迷失在实际的文件结构上。

任何帮助或建议都值得赞赏!

0 个答案:

没有答案