C/C++操作MySQL数据库——增、删、改、查

1、数据库链接

int cppDatebase::DatabaseConnect(sBit8 *uName,sBit8 *pWord,sBit8 *dbName)

{

  dbHandle = mysql_init(NULL);
  if(NULL == dbHandle )
  {
    cout<<"mysql init error!"<<endl;
    return (-1);
  }  

  if(NULL == mysql_real_connect(dbHandle ,"localhost",uName,pWord,dbName,0,NULL,0))

  {
    cout<<"connect error!"<<endl;
    return (-1);
  }

  mysql_set_character_set(dbHandle ,"utf8");

  return 0;

}

 

2、数据库插入——增

int cppDatebase::DatabaseInsert(const char *cmd)
{
  if(NULL == cmd)
  {
    cout<<"[insert] cmd error"<<endl;
    return (-1);
  }

  int ret = mysql_query(dbHandle,cmd);
  if(ret !=0)
  {
    cout << "Database Insert Info: exist, I am updata." <<endl<<endl;
    return (-1);
  }

  return 0;
}

 

3、数据库删除——删

int cppDatebase::DatabaseDelete(const char *cmd)
{
  if(NULL == cmd)
  {
    cout<<"[delete] cmd error"<<endl;
    return (-1);
  }

  int ret = mysql_query(dbHandle,cmd);
  if(ret !=0)
  {
    cout << "Database Delete Info: not exist." <<endl<<endl;
    return (-1);
  }

  return 0;
}

 

4、数据库更新——改

int cppDatebase::DatabaseUpdate(const char *cmd)
{
  if(NULL == cmd)
  {
    cout<<"[update] cmd error"<<endl;
    return (-1);
  }

  int ret = mysql_query(dbHandle,cmd);
  if(ret !=0)
  {
    cout << "Database Update Info: not exist, I am insert." <<endl<<endl;
    return (-1);
  }

  return 0;
}

 

5、数据库查询——查

int cppDatebase::DatabaseQuery(char *cmd, char **row)
{
  if(NULL == cmd || NULL == row)
  {
    cout<<"[query] cmd error"<<endl;
    return (-1);
  }

  mysql_real_query(dbHandle,cmd,strlen(cmd));

  MYSQL_RES *result = mysql_store_result(dbHandle);
  if(result != NULL)
  {
    int numLine = mysql_num_rows(result);
    int numList = mysql_num_fields(result);
  }
  else
  {
    cout<<"[query] mysql_store_result error !"<<endl;
    return (-1);
  }
  while((row = mysql_fetch_row(result)))
  {
    printf("%s, %s %s %s\n",row[0],row[1],row[2],row[3]);
  }
  mysql_free_result(result);

  return 0;
}

 

6、数据库断开

int cppDatebase::DatabaseClose()
{
  mysql_close(dbHandle);

  return 0;
}

你可能感兴趣的:(mysql)