C++ Mysql 通用代码

bool myUnit::ConnectDB()
{
	MYSQL *mysql = NULL;
	mysql = mysql_init(&m_mysql);
	if (!mysql){
		errorIntoMySQL();
		return FALSE;
	}
	mysql_options(&m_mysql, MYSQL_SET_CHARSET_NAME, "gbk");
	mysql = mysql_real_connect(&m_mysql, HOST, USER, PASSW, DBNAME, PORT, NULL, 0);
	if (mysql == NULL){
		errorIntoMySQL();
		return FALSE;
	}
	SpeakString("Database connected successful");
	return TRUE;
}

建立数据库

//判断数据库是否存在,不存在则创建数据库,并打开,输入数据库名字
bool myUnit::createDatabase(std::string& dbname){
	std::string queryStr = "create database if not exists ";
	queryStr += dbname;
	if (0 == mysql_query(&m_mysql, queryStr.c_str())){
		queryStr = "use ";
		queryStr += dbname;
		if (0 == mysql_query(&m_mysql, queryStr.c_str())){
			return true;
		}

	}
	errorIntoMySQL();
	return false;
}

建立表格

//判断数据库中是否存在相应表,不存在则创建表,输入的是对应的建表sql语句
bool myUnit::createdbTable(const std::string& query){
	if (0 == mysql_query(&m_mysql, query.c_str())){
		return true;
	}
	errorIntoMySQL();
	return false;
}

数据库初始化时建立库和表格 

myUnit::myUnit()
	只调用一次,建库、建表	
	std::string database ="facelib";
	createDatabase(database);
	std::string tableName = "face";
	std::string tableSql = "create table " + tableName + " (" +
	"name varchar(50) not null," +
	"feature varchar(10240)," +
	"pictureName varchar(1024)," +
	"primary key (name)" +
	"); ";
	createdbTable(tableSql);
}

查询语句,以输入名查找或全部select

//查询数据
bool myUnit::SelectDB(bool b, std::string m_name, std::vector<std::vector<std::string> > &data){
	std::string query;
	if (!b){
		if (m_name.length() == 0){
			AfxMessageBox("输入姓名不能为空!");
			return FALSE;
		}
		query = "select * from `face` where name = '" + m_name + "';";
	}
	else{
		query = "select * from `face`;";
	}
	//读取数据
	if (0 != mysql_query(&m_mysql, query.c_str())){
		errorIntoMySQL();
		return false;
	}
	result = mysql_store_result(&m_mysql);
	int row = mysql_num_rows(result);
	int field = mysql_num_fields(result);

	MYSQL_ROW line = NULL;
	line = mysql_fetch_row(result);
	std::string temp;
	while (NULL != line){
		std::vector<std::string> linedata;
		for (int i = 0; i<field; i++){
			if (line[i]){
				temp = line[i];
				linedata.push_back(temp);
			}
			else{
				temp = "NULL";
				linedata.push_back(temp);
			}
		}
		line = mysql_fetch_row(result);
		data.push_back(linedata);
	}
	return true;
}

插入语句 

bool myUnit::InsertDB(std::string m_name){
	if (m_name.length() == 0){
		SpeakString("人名不能为空!");
		return FALSE;
	}
	std::string str = "insert into `face` values('" + m_name + "','" + "NULL" + "','" + "NULL" + "');";
	if (mysql_query(&m_mysql, str.c_str())){
		errorIntoMySQL();
		return FALSE;
	}
	return TRUE;
}

删除

//删除数据
bool myUnit::DeleteDB(std::string m_name){
	//UpdateData(TRUE);
	if (m_name.length() == 0){
		SpeakString("人名不能为空!");
		return FALSE;
	}
	std::string query = "delete from `face` where name = '" + m_name + "';";
	if (mysql_query(&m_mysql, query.c_str())){
		errorIntoMySQL();
		return FALSE;
	}
	return TRUE;
}

删除数据

//读取数据
bool myUnit::getDatafromDB(std::vector<std::vector<std::string> >& data){
	std::string queryStr = "select * from `face`;";
	if (0 != mysql_query(&m_mysql, queryStr.c_str())){
		errorIntoMySQL();
		return false;
	}
	result = mysql_store_result(&m_mysql);
	int row = mysql_num_rows(result);
	int field = mysql_num_fields(result);

	MYSQL_ROW line = NULL;
	line = mysql_fetch_row(result);
	std::string temp;
	while (NULL != line){
		std::vector<std::string> linedata;
		for (int i = 0; i<field; i++){
			if (line[i]){
				temp = line[i];
				linedata.push_back(temp);
			}
			else{
				temp = "NULL";
				linedata.push_back(temp);
			}
		}
		line = mysql_fetch_row(result);
		data.push_back(linedata);
	}
	return true;
}

头文件
 

#pragma once

//#include "face_tai_sdklib.h"
//#include <mutex>

#include "speakInterface.h"

#include "resource.h"
#include <mysql.h>
#include <vector>
#include <string>
#include <vector>
#include <mutex>

#define HOST	"127.0.0.1"
#define USER	"root"
#define PASSW	"root"
#define DBNAME  "facelib"
#define PORT    3306

#pragma comment(lib, "ws2_32.lib")  
#pragma comment(lib, "libmysql.lib") 

// FaceLibManagerDlg 对话框
//#define pUnit ( &(myUnit::instance()) )


class myUnit {
	
public:
	static myUnit& instance();
	
	static bool MatchFeaturesFromMySQL(std::string strFile1, std::string& nameOfPeope, std::string& picName, std::string& addr,
		std::string& id, std::string& tel, std::string&  brith, std::string& gender, std::string& score, std::string& level, int& Ret);

	static bool createDatabase(std::string& dbname);
	static bool createdbTable(const std::string& query);
	static void errorIntoMySQL();
	static bool getDatafromDB(std::vector<std::vector<std::string> >& data);

	static bool ConnectDB();
	static bool SelectDB(bool b, std::string m_name, std::vector<std::vector<std::string> > &data);
	static bool InsertDB(std::string m_name, std::string m_pictureName, std::string m_addr, std::string m_id, std::string m_tel,
		std::string m_brith, std::string m_gender, std::string m_score, std::string m_level);
	static bool InsertDB(std::string m_name, std::string m_pictureName);
	static bool InsertDB(std::string m_name);
	static bool DeleteDB(std::string m_name);
	static void freeMSQL();
	static void SavePicInMySQL(char* strFile1);

	static void faceInit();
	static void faceExit();

public:

	static int errorNum;
	static const char* errorInfo;
	static MYSQL_RES *result;

	static MYSQL m_mysql;			//数据库结构
	static MYSQL_RES* m_res;     //查询的返回结果集
	static MYSQL_ROW m_row;      //获取每一条记录

	static int hCtx;
	static int m_nRet;
	static std::vector<std::vector<std::string> > m_vec;
	static std::mutex m_mutex;
	
};

表的增删改查

#查询

select 需查数据 ,需查数据 from 表名   //查询整个表中的某些数据

select * from 表名   //罗列整个表

select * from 表名 where salary>5000 (“条件查询” salary>50 表示工资大于5000的成员)
//查询整个表满足条件的数据,可以有多个条件,每个条件中用 and 连接

select * from 表名 where 列名 like "%小%";
//查询该列中带有 "小" 字的所有数据信息

select count(*) from 表名
//查询表中数据总个数

select avg(列名) from 表名 where(条件)
//查询满足条件的列中数据的平均值

select max(列名) from 表名 where(条件)
//查询满足条件的列中数据的最大值

select min(列名) from 表名 where(条件)
//查询满足条件的列中数据的最小值

select sum(列名) from 表名 where(条件)
//查询满足条件的列中数据的总和

#增加

对应插入:
INSERT into 表名(列名,列名,列名,列名  注意用逗号分隔) value('张为剑',2190.6,2,19889007867);
//表名列名一一对应,没有则插入 NULL 插入空需要考虑 该列能否为空 一般主列不可为空

依次插入:
insert into 表名 values(NULL, "张三", "男", 20, "18889009876");
括号内的数据依次放入表中,不输入用NULL占位 同样需要考虑 该列是否为空

#修改

update 表名 set age=age+1;
//将该表中的所有age都增加1

update 表名 set age(列名)=age+1 where id=7
//条件修改,修改满足条件id=7的行中的age列,使其加一

update 表名 set name='张汇美' where id=4;
//修改编号4的成员name列的名字为“张汇美”

update 表名 set age=90,name=CONCAT(name,'(老人)') where age>=80 and sex='女';
//修改并增加,将满足条件年龄大于80的女性的age列修改为90并在名字后增加“老人”的字符串
//CONCAT(str1,str2,...) 用于连接字符串连接str1、str2等

#删除

delete from 表名;
//删除表中所有数据,不删除表

delete from 表名 where id=8(删除满足条件的数据)
//删除id为8的一整行

 

对表的操作

修改表:
alter table 语句用于创建后对表的修改

1.添加列
alter table 表名 add 列名 列数据类型 [after 插入位置];

在表的最后追加列 address: 
alter table students add address char(60);

在名为 age 的列后插入列 birthday: 
alter table students add birthday date after age;

2.修改列
alter table 表名 change 列名称 列新名称 新数据类型;

将表 tel 列改名为 phone: 
alter table students change tel phone char(12) default "-";

将 name 列的数据类型改为 char(9): 
alter table students change name name char(9) not null;

3.删除列
alter table 表名 drop 列名称;

删除 age 列: alter table students drop age;

4.重命名表
基本形式: alter table 表名 rename 新表名;

重命名 students 表为temp: 
alter table students rename temp;

5.删除表
基本形式: drop table 表名;

删除students表: 
drop table students;

6.删除数据库
drop database 数据库名;

删除lcoa数据库: 
drop database lcoa;

 

数据库数据类型:
数字类型

整数: tinyint(一个字节)、smallint(两个字节)、mediumint(三个字节)、int(四个字节)、bigint(八个字节)
浮点数: float、double、real、decimal
日期和时间: date、time、datetime、timestamp、year

字符串类型
字符串: char、varchar(灵活的储存字符串)
varchar:
使用额外的1-2字节来存储值长度,列长度<=255使用1字节保存,其它情况使用2字节保存。
例如varchar(10)会占用11字节存储空间,varchar(500)会占用502字节存储空间。

文本: tinytext、text、mediumtext、longtext

二进制(可用来存储图片、音乐等): tinyblob、blob、mediumblob、longblob

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章