mysql C API statment and bind 执行查询

本文介绍了一个使用 C++ 进行 MySQL 数据库操作的示例程序,展示了如何通过预编译语句进行数据查询及插入操作。该示例包括了数据库连接、SQL 语句准备与执行等关键步骤。

#include <string>
#include <mysql/mysql.h>
#include <default.h>

typedef std::string string;

struct mysql_parm{
 string host;
 string user;
 string password;
 string database;
 string unixsock;
};
class DBSTMT;
class DBMysql;

class DBSTMT{
 DBSTMT(const DBSTMT&);
 DBSTMT& operator=(const DBSTMT&);
 MYSQL_STMT* stmt_;
public:
 DBSTMT(pcsz_t query,DBMysql& mysql);
 void execute(){
  if(mysql_stmt_execute(stmt_))
   throw mysql_stmt_error(stmt_);
 }
 
 void execute(MYSQL_BIND* bind){
  if(mysql_stmt_execute(stmt_))
   throw mysql_stmt_error(stmt_);
  if(mysql_stmt_bind_result(stmt_,bind)){
   throw mysql_stmt_error(stmt_);
  }
  if(mysql_stmt_store_result(stmt_))
   throw mysql_stmt_error(stmt_);
 }

 //void execute(){
 // if(mysql_stmt_execute(stmt_))
 //  throw mysql_stmt_error(stmt_);
 //}
 
 void bind(MYSQL_BIND* bind){
  if(mysql_stmt_bind_param(stmt_,bind) )
   throw mysql_stmt_error(stmt_);
 }
 
 int fetch(){
  return mysql_stmt_fetch(stmt_)==0;
 }
 ~DBSTMT(){
  if(stmt_){
   mysql_stmt_close(stmt_);
  }
 }
 
};


class DBMysql{
 DBMysql(const DBMysql&);
 DBMysql&operator=(const DBMysql&);
MYSQL * mysqlPtr_;

uint32_t errno_;
protected:
 friend class DBSTMT;
 MYSQL_STMT* _createSTMT(){
  MYSQL_STMT *ret=mysql_stmt_init(mysqlPtr_);
  if(ret)
   return ret;
  errno_=mysql_errno(mysqlPtr_);
  throw mysql_error(mysqlPtr_);
 }
public:
 const char* strerr(){
  return mysql_error(mysqlPtr_);
 }
 DBMysql():mysqlPtr_(NULL){
  mysqlPtr_=mysql_init(NULL);
  if(NULL== mysqlPtr_)
   throw "Mysql :outof memory";
 }
 void open(const mysql_parm& parm){
  if(!mysql_real_connect(mysqlPtr_,
   parm.host.c_str(),
   parm.user.c_str(),
   parm.password.c_str(),
   parm.database.c_str(),
   0,
   parm.unixsock.c_str(),
   0 ))
  {
   errno_=mysql_errno(mysqlPtr_);
   throw(mysql_error(mysqlPtr_));
  }
 }

 void close(){
  if(mysqlPtr_)
  {
   mysql_close(mysqlPtr_);
   mysqlPtr_=NULL;
  }
 }
  
};


DBSTMT::DBSTMT(pcsz_t query,DBMysql& mysql):stmt_(NULL){
 stmt_=mysql._createSTMT();
 if(!stmt_)
  throw mysql.strerr();
 if( mysql_stmt_prepare(stmt_,query,strlen(query)) )
 {
  //const char* err=
  
  throw mysql_stmt_error(stmt_);
 }
 
}


struct account{
 char user[36];
 byte password[16];
 uint32_t status;
 uint32_t id;
};

#define DECL_BIND(h,n)/
class bind_##h:public h{/
 typedef h parent;/
 MYSQL_BIND  _bind[n];/
 my_bool   _is_null[n];/
 unsigned long _length[n];/
public:/
 bind_##h(){/
  int i=0;/
  bzero(_bind,sizeof(_bind));


#define BIND_BIN(x,l)/
 _bind[i].buffer_type= MYSQL_TYPE_STRING;/
 _bind[i].buffer= (char *)&(parent::x);/
 _bind[i].buffer_length= l;/
 _bind[i].is_null= _is_null+i;/
 _bind[i].length= _length+i;/
 ++i;

#define BIND_INT(x)/
 _bind[i].buffer_type= MYSQL_TYPE_LONG;/
 _bind[i].buffer= (char *)&(parent::x);/
 _bind[i].buffer_length= 0;/
 _bind[i].is_null= _is_null+i;/
 _bind[i].length= _length+i;/
 ++i;

#define END_BIND(h)  }/
 operator MYSQL_BIND*(){/
 return _bind;/
 }/
};


//account acc;
//
//DECL_BIND(4)
// BIND_BIN(acc.user,32);
// BIND_BIN(acc.password,16);
// BIND_INT(acc.status);
// BIND_INT(acc.id);

// smt.executeAndStore(bind);
//END_BIND(4)

DECL_BIND(account,4)
 BIND_BIN(user,32)
 BIND_BIN(password,16)
 BIND_INT(status)
 BIND_INT(id)
END_BIND(account)

int main(){

 try{
  
  DBMysql mysql;
  mysql_parm parm;
  parm.host="localhost";
  parm.user="root";
  parm.password="mypwd";
  parm.unixsock="/var/lib/mysql/mysql.sock";
  parm.database="testdb";
  mysql.open(parm);
  
  DBSTMT smt("select user,password,status,id from account",mysql);
  DBSTMT smt1("insert into account(user,password,status) value(?,?,?)",mysql);
 //
  
  bind_account acc;
  
  smt.execute(acc);
  
  while(smt.fetch()){
   //acc.user[length[0]]=0;
   //acc.user,
   printf("%s %d %d/n",acc.user,acc.status,acc.id);
   //printf("%d %d/n",acc.status,acc.id);
   
   ;
   
  };
  smt1.bind(acc);
  smt1.execute();
  
  
  
 }catch(const char* err){
  printf("error:%s/n",err);
 }
 
 return 0;
 
}


### 使用 `if` 条件语句结合 `AND OR` 在编程中,条件语句用于控制程序流程,使得只有当特定条件满足时才会执行某些代码。对于 Python 中的 `if` 语句,可以配合逻辑操作符 `and` 和 `or` 实现更加复杂的条件判断。 #### 基本形式 基本的 `if` 语句结构允许通过指定单一条件来决定是否执行一段代码: ```python if condition: # 执行这段代码如果条件为真 ``` 为了增加灵活性并简化多条件表达式的编写,在某些场景下可以直接使用 `and/or` 组合代替嵌套的 `if...elif...else` 结构[^2]。这种做法依赖于 Python 对布尔值求值的方式以及短路评估机制。 #### 复杂条件下的应用实例 考虑这样一个例子:假设有一个列表 `l` 并希望获取第一个元素作为变量 `x` 的值;但如果列表为空,则赋予默认值 `None`: ```python x = len(l) > 0 and l[0] or None ``` 这里的关键在于理解这条语句是如何工作的: - 当 `len(l)>0` 成立(即列表不为空),整个表达式会返回 `l[0]`; - 如果上述条件失败(意味着列表确实为空),则最终结果将是右侧的操作数 `None`。 需要注意的是这种方式虽然简洁但是可能不够直观,并且容易引起误解特别是对于初学者来说。因此建议谨慎采用此技巧除非非常熟悉其工作原理及其潜在风险。 #### 完整示例展示 下面给出一个完整的案例说明如何在一个函数内部安全有效地运用这些概念: ```python def get_first_element(lst, default=None): """Return the first element of a list or a specified default value.""" result = lst and lst[0] or default return result # 测试用例 test_list_1 = [] print(get_first_element(test_list_1)) # 输出: None test_list_2 = ['apple', 'banana'] print(get_first_element(test_list_2)) # 输出: apple ``` 尽管如此,推荐的做法还是显式地写出所有的分支情况以便提高可读性和维护性: ```python def safer_get_first_element(lst, default=None): if not lst: return default else: return lst[0] # 同样的测试用例适用于此处... ``` 这种方法不仅更容易被其他开发者理解和调试,而且减少了因隐含行为而导致错误的可能性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值