我正在尝试创建一个连接到mysql的c程序,它可以对数据库执行诸如add-remove和edit之类的操作。对于每个表,我希望能够根据需要添加、删除和编辑以及运行特定的查询。到目前为止,我把所有的东西都放在一个主文件中,因为我不知道如何将代码划分成一个连接,然后调用其他类来运行查询。我显然是一个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
}
我想的是一个main,它调用一个person类,这个类连接到mysql,每个表都有一个类,它有自己的连接,但是我得到了seg错误
我的代码可以连接和编辑数据库正确,我只是迷失在实际的文件结构。
任何帮助或建议都将不胜感激!
暂无答案!
目前还没有任何答案,快来回答吧!