#include "UserManager.h"
using namespace std;
UserManager::UserManager() {
con = mysql_init(NULL);
//设置字符编码
mysql_options(con, MYSQL_SET_CHARSET_NAME, "GBK");
if (!mysql_real_connect(con, host, user, pw, database_name, port, NULL, 0))
{
std::cout << "Failed to connect with database";
exit(1);
}
}
UserManager::~UserManager() {
mysql_close(con);
}
bool UserManager::insert_user(User& user)
{
char sql[8192];
sprintf_s(sql, "insert into user(id,username,password) values (%d,'%s',%d)", user.id, user.username.data(), user.password);
if (mysql_query(con, sql))
{
fprintf(stderr, "Failed to insert data,Error:%s\n", mysql_error(con));
return false;
}
return true;
}
bool UserManager::delete_user(User& user)
{
char sql[8192];
sprintf_s(sql, " DELETE FROM user WHERE id=%d", user.id);
if (mysql_query(con, sql))
{
fprintf(stderr, "Failed to delete data,Error:%s\n", mysql_error(con));
return false;
}
return true;
}
bool UserManager::update_user(User& user)
{
char sql[8192];
sprintf_s(sql, " UPDATE user SET username='%s',password=%d WHERE id=%d",
user.username.data(), user.password,user.id);
if (mysql_query(con, sql))
{
fprintf(stderr, "Failed to updata data,Error:%s\n", mysql_error(con));
return false;
}
return true;
}
vector<User> UserManager::query_user(string condition)
{
vector<User> userList;
char sql[8192];
sprintf(sql, " SELECT * FROM user %s",condition.c_str());
if (mysql_query(con, sql))
{
fprintf(stderr, "Failed to select data,Error:%s\n", mysql_error(con));
return {};
}
MYSQL_RES* res = mysql_store_result(con);
MYSQL_ROW row;
while ((row = mysql_fetch_row(res)))
{
User user;
user.id = atoi(row[0]);
user.username = atoi(row[1]);
user.password = atoi(row[2]);
userList.push_back(user);
}
for (int i = 0; i < userList.size(); i++)
{
cout << userList[i].id << "," << userList[i].username << "," << userList[i].password << endl;
}
return userList;
}