1.安装mysql
sudo apt-get install mysql-server mysql-client
安装过程中会提示设置用户名和密码
2.启动mysql
sudo /etc/init.d/mysql restart
3.安装C++开发库
sudo apt-get install libmysqlclient-dev
4.登录mysql,并创建表
mysql -u root -p
--表maxPromised
CREATE TABLE maxPromised(id BIGINT auto_increment primary key, lock_name varchar(128), instance_no BIGINT, ballot_no BIGINT, unique uniq_lock_num(`lock_name`,`instance_no`)) engine=innodb default charset=utf8;
--表maxAccepted
CREATE TABLE maxAccepted(id BIGINT auto_increment primary key, lock_name varchar(128), instance_no BIGINT, ballot_no BIGINT, usid char(37), val_len int, val_str varchar(128),unique uniq_lock_num(`lock_name`,`instance_no`)) engine=innodb default charset=utf8;
5.代码片段
#include <mysql/mysql.h>//连接数据库
MYSQL *conn = mysql_init(NULL);
if (conn == NULL) {
LOGGER(ERROR)<<mysql_errno(conn)<<": "<<mysql_error(conn);
exit(1);
}
if (mysql_real_connect(conn, "localhost", "root", "themis", "themis", 0, NULL, 0) == NULL) {
LOGGER(ERROR)<<mysql_errno(conn)<<": "<<mysql_error(conn);
exit(1);
}
//插入
char query[MAX_SQL_STMT_SIZE];
sprintf(query, "INSERT INTO maxPromised(lock_name, instance_no, ballot_no) VALUES("%s",%lu,%lu);",
“field“,
1L,
0L
);
if(mysql_query(acceptor->conn, query) != 0){
LOGGER(ERROR)<<"Failed:"<<query;
}
//更新
sprintf(query, "UPDATE maxPromised set ballot_no = %lu WHERE lock_name = "%s" AND instance_no = %lu;",
1,
“field”,
3
);
if(mysql_query(acceptor->conn, query) != 0){
LOGGER(ERROR)<<"Failed:"<<query;
//查询数据库
MYSQL_RES *result;
MYSQL_ROW row;
char query[MAX_SQL_STMT_SIZE];
sprintf(query, "SELECT * FROM maxAccepted_%d", id);
mysql_query(conn, query);
result = mysql_store_result(conn);
while (result && (row = mysql_fetch_row(result))) {
const char* field = row[1];
long iid = atol(row[2]);
long bno = atol(row[3]);
printf("%s, %lu, %lun", field, iid, bno);
}
mysql_free_result(result);
//关闭数据库
mysql_close(conn);