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

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