C++常用库和代码

Mysal_C++

安装和配置

安装

1
2
3
sudo apt-get install mysql-server
sudo apt-get install mysql-client
sudo apt-get install libmysqlclient-dev

启动mysql-server

1
sudo service mysql start

登录mysql-server

1
sudo mysql -u 用户名 -p

使用C++:

头文件

1
#include <mysql.h>

连接

mysql_real_connect函数原型:

1
2
3
4
5
6
7
8
9
10
11
12
MYSQL *mysql_real_connect (
MYSQL *mysql, // MYSQL*连接句柄。
const char *host, // 可以是一个主机名或一个IP地址。如果host是NULL或字符串"localhost",表示是到本地主机的一个连接。
const char *user, // 用户名
const char *passwd, // 密码
const char *db, // 要连接的数据库名称
unsigned int port, // 端口
const char *unix_socket, // 如果unix_socket不是NULL,字符串指定套接字或应该被使用的命名管道。
unsigned long client_flag //通常是0
)

返回值用于判断连接是否成功,如果连接成功,返回值应该和第一个参数相同,否则返回NULL

示例:

1
2
3
4
5
6
7
MYSQL conn;
mysql_init(&conn); // 要先初始化
if(mysql_real_connect(&conn, "localhost", "root", "password", "test", 3306, NULL, CLIENT_FOUND_ROWS)){
cout << "connect success" << endl;
}else{
printf("OK\n");
}

查询

mysql_query函数原型:

1
2
3
4
int mysql_query(
MYSQL *mysql, //数据库句柄
const char *query // 要执行的语句
)

示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
std::string query = "select * from test";
if(mysql_query(&conn, query.c_str())){
std::cout << "query error" << std::endl;
std::cout << "Query failed: " << mysql_error(&conn) << std::endl;
}
MYSQL_RES* res = NULL;
res = mysql_store_result(&conn);
if(!res){
std::cout << "can not read result " << mysql_error(&conn) << std::endl;
}

std::cout << "number of dataline returned: " << mysql_affected_rows(&conn) << std::endl;

// 获取列数
int j = mysql_num_fields(res);

//存储字段信息
char *str_field[32];

//获取字段名
for (int i = 0; i < j; i++){
str_field[i] = mysql_fetch_field(res)->name;
}

//打印字段
for (int i = 0; i < j; i++)
printf("%10s\t", str_field[i]);
printf("\n");

MYSQL_ROW column; //数据行的列
//打印查询结果
//MYSQL_ROW mysql_fetch_row(MYSQL_RES *result)
//Fetches the next row from the result set
while (column = mysql_fetch_row(res)){
printf("%10s\t%10s\n", column[0], column[1]);
}

插入&修改&删除

使用mysql_query

释放资源

1
2
3
4
void FreeConnect(){
mysql_free_result(res);
mysql_close(&conn);
}

另一个示例代码

来源:https://www.cnblogs.com/iwangzhengchao/p/10056075.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
/*
C/C++连接MySQL数据库时,需要包含一个*.h的mysql头文件和一个mysql的lib文件
1、初始化;2、连接数据库;3、执行sql查询语句;4、获取查询值;5、关闭
*/
#include <stdio.h>
#include <WinSock.h>
#include <mysql.h>
#include <Windows.h>
#pragma comment(lib,"wsock32.lib")
#pragma comment(lib,"libmysql.lib")

MYSQL mysql;
MYSQL_FIELD *fd; //字段列数组
char field[32][32]; //存字段名二维数组
MYSQL_RES *res; //行的一个查询结果集
MYSQL_ROW column; //数据行的列
char query[150]; //查询语句

//函数声明
bool ConnectDatabase();
void FreeConnect();
bool QueryDatabase();
bool InsertData();
bool ModifyData();
bool DeleteData();

int main(int argc, char **argv){
ConnectDatabase();
QueryDatabase();
InsertData();
QueryDatabase();
ModifyData();
QueryDatabase();
//DeleteData();
//QueryDatabase();
FreeConnect();
system("pause");
return 0;
}

//连接数据库
bool ConnectDatabase(){
//Gets or initializes a MYSQL structure
mysql_init(&mysql);

// Connects to a MySQL server
const char host[] = "localhost";
const char user[] = "root";
const char passwd[] = "root";
const char db[] = "employees";
unsigned int port = 3306;
const char *unix_socket = NULL;
unsigned long client_flag = 0;

/*A MYSQL* connection handler if the connection was successful,
NULL if the connection was unsuccessful. For a successful connection,
the return value is the same as the value of the first parameter.*/
if (mysql_real_connect(&mysql, host, user, passwd, db, port, unix_socket, client_flag)){
printf("The connection was successful.\n");
return true;
}
else{
/*const char *mysql_error(MYSQL *mysql)
Returns the error message for the most recently invoked MySQL function
A null-terminated character string that describes the error.
An empty string if no error occurred.*/
printf("Error connecting to database:%s\n", mysql_error(&mysql));
return false;
}
}

//释放资源
/*void mysql_free_result(MYSQL_RES *result)
Frees the memory allocated for a result set by mysql_store_result(),
mysql_use_result(), mysql_list_dbs(), and so forth.When you are done
with a result set, you must free the memory it uses by calling mysql_free_result().
Do not attempt to access a result set after freeing it.*/

/*void mysql_close(MYSQL *mysql)
Closes a previously opened connection.mysql_close() also deallocates
the connection handler pointed to by mysql if the handler was allocated
automatically by mysql_init() or mysql_connect().*/
void FreeConnect(){
mysql_free_result(res);
mysql_close(&mysql);
}

//查询数据
bool QueryDatabase(){
//将数据格式化输出到字符串
sprintf_s(query, "select * from departments");
//设置编码格式
mysql_query(&mysql, "set names gbk");

/*int mysql_query(MYSQL *mysql, const char *stmt_str)
Executes an SQL query specified as a null-terminated string
Executes the SQL statement pointed to by the null-terminated string stmt_str.
Normally, the string must consist of a single SQL statement without
a terminating semicolon (;). If multiple-statement execution has been enabled,
the string can contain several statements separated by semicolons.
Return Values:Zero for success. Nonzero if an error occurred.*/
if (mysql_query(&mysql, query)){
printf("Query failed (%s)\n", mysql_error(&mysql));
return false;
}
else{
printf("query success\n");
}

/*MYSQL_RES *mysql_store_result(MYSQL *mysql)
Retrieves a complete result set to the client
mysql_store_result() reads the entire result of a query to the client,
allocates a MYSQL_RES structure, and places the result into this structure.
mysql_store_result() returns a null pointer if the statement did not return
a result set(for example, if it was an INSERT statement). mysql_store_result()
also returns a null pointer if reading of the result set failed.
You can check whether an error occurred by checking whether mysql_error()
returns a nonempty string. Return Values:A MYSQL_RES result structure with
the results.NULL(0) if an error occurred.*/
res = mysql_store_result(&mysql);
if (!res){
printf("Couldn't get result from %s\n", mysql_error(&mysql));
return false;
}

/*my_ulonglong mysql_affected_rows(MYSQL *mysql)
It returns the number of rows changed, deleted,
or inserted by the last statement if it was an UPDATE, DELETE, or INSERT.
For SELECT statements, returns the number of rows in the result set.*/
printf("number of dataline returned: %d\n", mysql_affected_rows(&mysql));

/*MYSQL_FIELD *mysql_fetch_field(MYSQL_RES *result)
Returns the definition of one column of a result set as a MYSQL_FIELD structure.
Call this function repeatedly to retrieve information about all columns in the result set.*/

// 获取列数
int j = mysql_num_fields(res);

//存储字段信息
char *str_field[32];

//获取字段名
for (int i = 0; i < j; i++){
str_field[i] = mysql_fetch_field(res)->name;
}

//打印字段
for (int i = 0; i < j; i++)
printf("%10s\t", str_field[i]);
printf("\n");

//打印查询结果
//MYSQL_ROW mysql_fetch_row(MYSQL_RES *result)
//Fetches the next row from the result set
while (column = mysql_fetch_row(res)){
printf("%10s\t%10s\n", column[0], column[1]);
}
return true;
}

//插入数据
bool InsertData(){
sprintf_s(query, "insert into departments values ('xxxx', 'xxxxx');");
if (mysql_query(&mysql, query)) {
printf("Query failed (%s)\n", mysql_error(&mysql));
return false;
}
else{
printf("Insert success\n");
return true;
}
}

//修改数据
bool ModifyData(){
sprintf_s(query, "update departments set dept_name='yyyyy' where dept_no='xxxx'");
if (mysql_query(&mysql, query)) {
printf("Query failed (%s)\n", mysql_error(&mysql));
return false;
}
else{
printf("Insert success\n");
return true;
}
}

//删除数据
bool DeleteData()
{
sprintf_s(query, "delete from departments where dept_no='xxxx';");
if (mysql_query(&mysql, query)) {
printf("Query failed (%s)\n", mysql_error(&mysql));
return false;
}
else{
printf("Insert success\n");
return true;
}
}

编译

1
g++ mysqltest.cpp `mysql_config --cflags --libs` -o mysqltest

线程库std::stread

thread

头文件:

1
<thread>

构造:

1
std::thread t(f, arg1, arg2, ……);

第一个参数是某个函数的地址,后面的参数是传递给该函数的参数。

线程启动后,会直接调用该函数。

如果函数是类的成员函数的话,需要添加该类的地址作为函数的第一个参数

如:

1
2
3
4
5
6
7
8
9
10
class A{
void f(int x);
};

int main(){
A a;
int x;
std::thread t(A::f, &a, x);
return 0;
}

join和detach

join方法:主线程启动线程并等待其执行结束后继续执行

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <thread>
#include <iostream>

void f(){
for(int i = 0; i < 10; ++i){
std::cout << i << std::endl;
}
}

int main(){
std::thread t(f);
t.join();
std::cout << "main" << std::endl;
return 0;
}

结果:

1
2
3
4
5
6
7
8
9
10
11
0
1
2
3
4
5
6
7
8
9
main

detech方法:创建线程后分离,主线程和子线程同时继续执行

主线程如果执行太快了,可能会来不及执行完子线程就结束,跟着杀死子线程

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <thread>
#include <iostream>

void f(){
for(int i = 0; i < 10; ++i){
std::cout << i << std::endl;
}
}

int main(){
std::thread t(f);
t.detach();
std::cout << "main" << std::endl;
return 0;
}

执行结果

1
2
3
4
5
6
7
8
9
10
11
main
0
1
2
3
4
5
6
7
8
9